JavaScript: Check if a string contains a substring.

This is a tutorial on how to check if a string contains a substring using JavaScript. To do this, we will be using 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. The indexOf() method will return a -1 (minus one) value if the given search term was not found inside the string. Therefore, if the return value is not -1, we can safely assume that the string does contains 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 can be found inside another string. This method can be used like so:

//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.
    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, this means that the method is not supported in Internet Explorer.

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 sizeable number of clients to be excluding.

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(search + ' was found inside the string: ' + string);

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:

ELlo was found inside the string: Hello! 123! Test!

Basically, our code was able to detect that the string contained the substring “ELlo”, despite the case.