How to Check if a String Contains a Substring in JavaScript

Sometimes it is necessary to find out if a string contains a word or another substring in JavaScript. Fortunately, JavaScript provides several ways to achieve this, which is what we will learn in this tutorial.

 

The includes() Method

The easiest way to check the presence of a pattern in a string in JavaScript is to use the built-in includes() method. To use this method, pass it after the string in question using a . (dot) and inside the parenthesis of includes() pass the substring you want to look for.

 

var string = 'this is some text';

var result = string.includes('text');

console.log(result);
true

 

includes() provides a boolean true or false response if the presence of a substring is found.

 

The includes() method is case sensitive. If you would like to perform a case insensitive check, convert both the string to search and value to check into lowercase using the toLowerCase() method.

 

var string = 'this is some text';

value = 'TeXt'.toLowerCase();
var result = string.toLowerCase().includes(value);

console.log(result);
true

 

Set a Starting Position to Check from

The includes() method accepts a second optional argument that specifies where to begin looking for a substring in the string. This numerical value represents the character position to check after.

 

var string = 'this is some text';

var result = string.includes('his', 1);
var result_2 = string.includes('his', 2);

console.log(result);
console.log(result_2);
true
false

 

Using indexOf()

includes() is supported by all modern browsers, however, if you need to be absolutely sure that checking for substrings works for users with outdated browsers use the indexOf() method. Here is are a couple of examples of indexOf() in action:

 

var string = 'this is some text';

var result = string.indexOf('his') !== -1;
var result_2 = string.indexOf('his', 2) !== -1;

console.log(result);
console.log(result_2);
true
false

 

Conclusion

You now know how to check if a substring can be found in a string in three different ways in JavaScript.