How to do String.contains(mySubString) in Javascript?

javascript

(SAM) #1

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

This wasn’t working for me:

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

(Yassine) #2

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.


(Tas Dever) #3

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.


(afree) #4

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().