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. (ES6) includes —go to answer

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. 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 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++;
}
链接地址: http://www.djcxy.com/p/22.html

上一篇: 如何在提交前撤销'git add'?

下一篇: 如何检查一个字符串是否包含JavaScript中的子字符串?