How to check whether a string contains a substring in JavaScript?


Usually I would expect a String.contains() method but there doesn't seem to be one. What is a reasonable way to check for this?



Answers



Here is a list of current possibilities:

1. indexOf

var string = "foo",
    substring = "oo";
string.indexOf(substring) !== -1;

String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

2. (ES6) includes - go to answer, or this answer

var string = "foo",
    substring = "oo";
string.includes(substring);

3. search - go to answer

var string = "foo",
    expr = /oo/;
string.search(expr);

4. lodash includes - go to answer

var string = "foo",
    substring = "oo";
_.includes(string, substring);

5. RegExp - go to answer

var string = "foo",
    expr = /oo/;  // no quotes here
expr.test(string);

6. Match - go to answer

var string = "foo",
    expr = /oo/;
string.match(expr);

Performance tests (http://jsben.ch/#/RVYk7) are showing that indexOf might be the best choice, if it comes to a point where speed matters.




You can easily add a contains method to String with this statement:

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

Note: see the comments below for a valid argument for not using this. My advice: use your own judgement.

Alternatively:

if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }



The problem with your code is that JavaScript is case sensitive. Your method call

indexof()

should actually be

indexOf()

Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {
    alert(elm);
    foundLinks++;
}



How do I check if string contains substring?

Like this:

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))



You could use search or match for this.

str.search( 'Yes' )

will return the position of the match, or -1 if it isn't found.




Another way:

var testStr = "This is a test";

if(testStr.contains("test")){
    alert("String Found");
}

** Tested on Firefox, Safari 6 and Chrome 36 **










Node.js: String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}