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?


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";

3. search - go to answer

var string = "foo",
    expr = /oo/;;

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

6. Match - go to answer

var string = "foo",
    expr = /oo/;

Performance tests ( 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.


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


should actually be


Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {

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)


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

You could use search or match for this. 'Yes' )

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

Another way:

var testStr = "This is a 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) {