Stopbyte

How to do string contains in Javascript?

How can I find if a given string contains another substring in Javascript.

This wasn’t working for me:

if (string.contains(mySubString)) {
    alert(MyString + " contains " + mySubString);
}
2 Likes

You may use this:

MyString.includes(mySubString)

That’s the equivalent of string.contains() in Javascript.

by the way, the includes() method can also take an optional “start” parameter, that indicates which position to start the search from (its default value is 0).

Thus, the full syntax of the string.includes() method becomes:

MyString.includes(mySubString, StartIndex);

P.S. As others mentioned below, .includes() is not majorly supported in older browsers (IE and Opera). So you may use indexOf() instead, which is not an exact match of includes() or contains() but it does the job really well. In fact, it can be way better than .includes() in terms of performance.

1 Like

string.includes("string") is not supported by all browsers, especially IE and Opera.

The most widely supported method is string.indexOf("string").

string.indexOf() returns the first index of the beginning of the string. thus it will be returning -1 if the string is not found and a positive number (position) if it can be found.

1 Like

Other than the options @Yassine and @Tas mentioned,

string.includes(); 
string.indexOf();

You can also use string.search() or string.match() for expression matching:

var string = "foobar", expression = "/bar/";
string.search(expression);
/* OR */
string.match(expression);

string.search() and string.match() look for an expression rather than a simple string, so it’s more usable compared to indexOf() or includes().

1 Like