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

Spread the love

Question Description

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?

Practice As Follows

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) includesgo to answer, or this answer

var string = "foo",
    substring = "oo";

3. searchgo to answer

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

4. lodash includesgo to answer

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

5. RegExpgo to answer

var string = "foo",
    expr = /oo/;  // no quotes here

6. Matchgo 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 may be interested in these books.

(paid link)

As an Amazon Associate I earn from qualifying purchases.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.