[The easy way to] check if a string contains a substring in Javascript

There are several methods to check if a substring is contained within a string in Javascript. Here are several methods that should work for you.

The easiest and most compatible method to find a substring within a string in Javascript is to use the match() function with a regular expression.

Find a substring with a regular expression (regex)

This method is compatible with all current versions of Javascript and very simple to use. Here is an example:

var myString = 'This is a javascript string.';

// The / and / set the substrings to regular expressions
var subString1 = /javascript/;
var subString2 = /python/;

myString.match(subString1); // [ 'javascript', index: 10, input: 'This is a javascript string.', groups: undefined ]
myString.match(subString1); // nullCode language: JavaScript (javascript)

To make it easy to use the results to test whether the substring exists or not, you can use the !! trick to convert the output to a boolean:

!!myString.match(subString1); // true
!!myString.match(subString1); // falseCode language: JavaScript (javascript)

Find a substring with the new includes() method

The includes() string method can also be used to find a substring within another string.

var myString = 'This is a javascript string.';

myString.includes('javascript'); // true
myString.includes('python'); // falseCode language: JavaScript (javascript)

Additional Resources

Recent Posts