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:

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:

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:

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.

Facebook Comments