Explain Codes LogoExplain Codes Logo

How to check whether a string contains a substring in JavaScript?

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Feb 15, 2025
TLDR
// The method is as simple as it looks const found = 'Your string'.includes('search term'); // true or false? That is the question!

For a rapid substring search, put includes() to work. This handy helper doles out a truthy true if the substring is detected, or dishes a falsey false if not. As a cheeky tip, remember it is case-sensitive for precise matches.

Weathering the compatibility storm

Suppose you're dealing with the likes of Internet Explorer, which often necessitates backwards compatibility. For older browsers, you find a reliable friend in indexOf():

var helloWorld = "Hello World!"; var world = "World"; console.log(helloWorld.indexOf(world) !== -1); // Find "World" in a haystack

indexOf() returns the position of the substring, or -1 if the substring has renounced its relationship with the original string — it's not a part of it.

To maintain evergreen compatibility, consider adopting a polyfill:

if (!String.prototype.includes) { String.prototype.includes = function(search, start) { if (typeof start !== 'number') { start = 0; } return this.indexOf(search, start) !== -1; }; }

Plug this retroactive tech-spray atop any includes() dependent code to ensure even cranky, old systems recognize it.

Keeping it classy with KMP

For complex yum cha sessions with more than dim sum-sized strings, a Knuth–Morris–Pratt algorithm can cater to your needs:

function kmpSearch(pattern, text) { // KMP algorithm in action here } // Call and order your answer console.log(kmpSearch("abc", "abcabcabcabc")); // First come, first served. Index of first match served here.

This algorithm whisks up an O(n+m) time complexity that's significantly snappier than native methods when dealing with strings longer than an epic spaghetti noodle. However, cooking up a KMP algorithm is often best suited to gourmet programming connoisseurs.

Mind the difference: Case and culture matter

String tests are case-sensitive:

console.log('JavaScript'.includes('script')); // false, JavaScript isn't fond of being written in lowercase console.log('JavaScript'.toLowerCase().includes('script'.toLowerCase())); // true, now it's-party time!

This example demonstrates how switching to the common ground of lowercase can lead to a match made in heaven.

Scaling the length of strings

For voluminous strings or heavy-duty text processing, native methods like includes() and indexOf() can seem as slow as a This could be your time complexity snail 🐌. Advanced string matching algorithms, however, bring out the racing horse 🏇 in your code.

Harness the power of regular expressions

Take the reins of your search criteria with regular expressions:

const regex = /term/i; // Set to 'i' for case 'in'sensitivity console.log(regex.test('Your string')); // Unleash the regex kraken!

Regular expressions are flexible, allowing you to match patterns using wildcards, quantifiers, and more.