如何在JavaScript中检查字符串是否包含子字符串?
这里有一个可用方法列表:
- (ES6) includes
var string = "foo",
substring = "oo";
string.includes(substring);
- 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.
- search
var string = "foo",
expr = /oo/;
string.search(expr);
- lodash includes
var string = "foo",
substring = "oo";
_.includes(string, substring);
- RegExp
var string = "foo",
expr = /oo/; // no quotes here
expr.test(string);
- Match
var string = "foo",
expr = /oo/;
string.match(expr);
性能测试表明,如果速度很重要,indexOf可能是最好的选择。