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

avatar
40    5 months ago

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 { 3 }
avatar
5 months ago

Here is a list of current possibilities:

1. (ES6) includesgo to answer (no IE support)

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

2. ES5 and older 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.

3. searchgo to answer

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

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
expr.test(string);

6. Matchgo to answer

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

Performance tests are showing that indexOf might be the best choice, if it comes to a point where speed matters.

avatar
5 months ago

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

avatar
5 months ago

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++;
}