我正在处理JavaScript的性能问题。所以我只想问:检查字符串是否包含另一个子字符串的最快方法是什么(我只需要布尔值)?您可以建议您的想法和示例代码片段吗?
当前回答
最快的
(ES6) includes
var string = "hello", substring = "lo"; string.includes(substring);
智慧指数
var string = "hello", substring = "lo"; string.indexOf(substring) !== -1;
http://jsben.ch/9cwLJ
其他回答
这是使用.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)));
祝您有愉快的一天,先生!
我做了一个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中显示的结果,它们似乎都表现得很好。
最快的
(ES6) includes
var string = "hello", substring = "lo"; string.includes(substring);
智慧指数
var string = "hello", substring = "lo"; string.indexOf(substring) !== -1;
http://jsben.ch/9cwLJ
根据这个网站,包含要快得多 https://www.measurethat.net/Benchmarks/Show/13675/0/regextest-vs-stringincludes-vs-stringmatch