在 JavaScript 中检查字符串是否包含另一个子字符串的最快方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5296268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:32:13  来源:igfitidea点击:

Fastest way to check a string contain another substring in JavaScript?

javascriptregexsubstring

提问by ?inh H?ng Chau

I'm working with a performance issue on JavaScript. So I just want to ask: what is the fastest way to check whether a string contains another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?

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

回答by Felix Kling

You have two possibilites:

你有两种可能:

  1. Regular expression:

    (new RegExp('word')).test(str)
    // or
    /word/.test(str)
    
  2. indexOf:

    str.indexOf('word') !== -1
    
  1. 正则表达式

    (new RegExp('word')).test(str)
    // or
    /word/.test(str)
    
  2. indexOf

    str.indexOf('word') !== -1
    

Regular expressions seem to be faster(at least in Chrome 10).

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

Performance test - short haystack
Performance test - long haystack

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



Update 2011:2011 年更新:

It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOfseems to be faster, in Safari 5, indexOfis clearly slower than any other method.

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

You have to see and try for your self. It depends on your needs. For example a case-insensitivesearch is way faster with regular expressions.

你必须看到并尝试自己。这取决于您的需求。例如,不区分大小写的搜索使用正则表达式会更快。



Update 2018:

2018 年更新:

Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):

为了避免人们自己运行测试,以下是大多数常见浏览器的当前结果,百分比表示性能比下一个最快的结果(因浏览器而异)有所提高:

Chrome:indexOf (~98% faster) <-- wow
Firefox:cached RegExp (~18% faster)
IE11:cached RegExp(~10% faster)
Edge:indexOf (~18% faster)
Safari:cached RegExp(~0.4% faster)

Chrome:indexOf(快 98%)<-- wow
Firefox:缓存 RegExp(快 18%)
IE11:缓存 RegExp(快 10%)
Edge:indexOf(快 18%)
Safari:缓存 RegExp(快 0.4%)

Note that cached RegExpis: var r = new RegExp('simple'); var c = r.test(str);as opposed to: /simple/.test(str)

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

回答by Stephen Chung

Does this work for you?

这对你有用吗?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

编辑:如果 string2 包含重复模式,这可能不会比 RegExp 快。在某些浏览器上,indexOf 可能比 RegExp 慢得多。看评论。

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

编辑 2:当字符串很长和/或包含重复模式时,RegExp 可能比 indexOf 快。查看评论和@Felix 的回答。

回答by Tính Ng? Quang

The Fastest

最快的

  1. (ES6) includes
  1. (ES6)包括
    var string = "hello",
    substring = "lo";
    string.includes(substring);
  1. ES5 and older indexOf
  1. ES5 及更早的indexOf
    var string = "hello",
    substring = "lo";
    string.indexOf(substring) !== -1;

http://jsben.ch/9cwLJ

http://jsben.ch/9cwLJ

enter image description here

在此处输入图片说明

回答by wpg4665

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAtperforms faster than indexOfor Regex. The code and proof is available at JSPerf.

我发现使用简单的 for 循环,遍历字符串中的所有元素并比较 using 的charAt执行速度比indexOfor快Regex。代码和证明可在JSPerf 获得

ETA: indexOfand charAtboth perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

ETA:根据 jsperf.com 上列出的浏览器范围数据indexOfcharAt两者在 Chrome Mobile 上的表现都同样糟糕

回答by zangw

In ES6, the includes()method is used to determine whether one string may be found within another string, returning trueor falseas appropriate.

在 ES6 中,该includes()方法用于确定一个字符串是否可以在另一个字符串中找到,返回truefalse适当。

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

Here is jsperfbetween

这里是jsperf之间

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

And

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

As the result shown in jsperf, it seems both of them perform well.

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

回答by Chii

For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring- so choose which ever one that seems easier to write.

为了找到一个简单的字符串,使用 indexOf() 方法和使用正则表达式几乎相同:http: //jsperf.com/substring- 所以选择看起来更容易编写的那个。

回答by EscapeNetscape

I made a jsben.ch for you http://jsben.ch/#/aWxtF...seems that indexOf is a bit faster.

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

回答by Anton Danilchenko

It's easy way to use .match()method to string.

使用.match()方法来串接是很简单的方法。

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

祝您有美好的一天,先生!