我正在处理JavaScript的性能问题。所以我只想问:检查字符串是否包含另一个子字符串的最快方法是什么(我只需要布尔值)?您可以建议您的想法和示例代码片段吗?


当前回答

在ES6中,includes()方法用于确定一个字符串是否可以在另一个字符串中找到,并根据需要返回true或false。

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false

这里是jsperf between

var ret = str.includes('one');

And

var ret = (str.indexOf('one') !== -1);

正如在jsperf中显示的结果,它们似乎都表现得很好。

其他回答

为了找到一个简单的字符串,使用indexOf()方法和使用regex方法几乎是一样的:http://jsperf.com/substring -所以选择哪个看起来更容易编写。

最快的

(ES6) includes

    var string = "hello",
    substring = "lo";
    string.includes(substring);

智慧指数

    var string = "hello",
    substring = "lo";
    string.indexOf(substring) !== -1;

http://jsben.ch/9cwLJ

你有三种可能:

正则表达式: (新的正则表达式(词))test (str) / /或 词/ test (str) indexOf: str.indexOf('word') !== -1 包括: str.includes(单词)

正则表达式似乎更快(至少在Chrome 10中)。

性能测试-短干草堆 性能测试-长干草堆


**Update 2011:**

不能肯定地说哪种方法更快。浏览器之间的差异是巨大的。虽然在Chrome 10中indexOf似乎更快,但在Safari 5中,indexOf明显比其他任何方法都要慢。

你必须自己去看,自己去尝试。这取决于你的需要。例如,不区分大小写的搜索使用正则表达式要快得多。


2018年更新:

为了避免人们自己运行测试,这里是大多数常见浏览器的当前结果,百分比表明性能比第二快的结果有所提高(不同浏览器的性能有所不同):

Chrome: indexOf(~98%快)<——哇 Firefox:缓存的RegExp(快18%) IE11:缓存的RegExp(快10%) Edge: indexOf(快18%) Safari:缓存RegExp(快0.4%)

注意缓存的RegExp是:var r = new RegExp('simple');Var c = r.test(str);而不是:/simple/.test(str)

我做了一个jsben。ch为你http://jsben.ch/#/aWxtF…似乎indexOf有点快。

在ES6中,includes()方法用于确定一个字符串是否可以在另一个字符串中找到,并根据需要返回true或false。

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false

这里是jsperf between

var ret = str.includes('one');

And

var ret = (str.indexOf('one') !== -1);

正如在jsperf中显示的结果,它们似乎都表现得很好。