JavaScript: Check if a string contains a substring.

This is a JavaScript tutorial on how to check if a string contains a substring or character.

To accomplish this, we will use the String.prototype.indexOf() method.

Take a look at the following example:

//The string that you want to search.
var string = 'Hello! 123! Test!';

//The substring that you want to search for.
var search = 'ello';

//If the indexOf method doesn't return -1, then
//the substring exists inside our string.
if(string.indexOf(search) !== -1){
    alert(search + ' was found inside the string: ' + string);
}

In the JavaScript snippet above, we searched our string for the substring “ello”.

We did this by using the indexOf() method. If the given search term is not found within the string, the indexOf method will return a -1 (minus one) value.

Therefore, if the return value is not -1, we can safely assume that the string does contain the substring we are looking for.

Note that you can also use this method to search for a single character.

Why not use the includes() method?

You can also use the String.prototype.includes() method to determine if one string exists inside another.

An example of the includes method:

//Our string.
var str = 'This is a test.';

//The search term we are looking for.
var searchTerm = 'test';

//Using the includes() method to check whether
//our string contains the search term.
if(str.includes(searchTerm)){
    alert('Substring found!');
}

As you can see, the code above is basically the same as the code in the first example.

However, the problem with “includes()” is that it was only introduced in ECMAScript 6.

As a result, older browsers such as Internet Explorer do not support it.

Unfortunately, as of 2019, IE still commands over 2% of the total market share for desktop computers. Personally, I think that this is still a sizable number.

Case insensitive substring search.

It is important to note that the String.prototype.indexOf() method is case-sensitive.

In order to do a case insensitive search for a substring, you will need to use the toUpperCase() method:

//The string that you want to search.
var string = 'Hello! 123! Test!';

//The substring that you want to perform
//a case insensitive search for.
var search = 'ELlo';

//In this example, we make both strings uppercase before
//we perform our substring search.
if(string.toUpperCase().indexOf(search.toUpperCase()) !== -1){
    alert('Our string contains the string: ' + search);
}

In the example above, we converted both strings to uppercase before we performed our substring search.

If you run this example, you will see that the output is:

Our string contains the string: ELlo

As you can see, our code was able to detect that the string contained the substring “ELlo”, despite the case.