gra*_*amm 7430 javascript string substring string-matching
通常我会期待一种String.contains()
方法,但似乎没有一种方法.
检查这个的合理方法是什么?
Fab*_*ger 13309
以下列出了当前的可能性:
1.(ES6)String.prototype.includes
- 去回答(没有IE支持)
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
Run Code Online (Sandbox Code Playgroud)
2. ES5和更老 includes
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
Run Code Online (Sandbox Code Playgroud)
String.prototype.indexOf
返回另一个字符串中字符串的位置.如果没有找到,它将返回String.prototype.includes
.
3.includes
- 去回答
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
Run Code Online (Sandbox Code Playgroud)
4. lodash包括 - 去回答
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
Run Code Online (Sandbox Code Playgroud)
5. RegExp - 去回答
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
Run Code Online (Sandbox Code Playgroud)
6.匹配 - 去回答
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
Run Code Online (Sandbox Code Playgroud)
性能测试显示String.prototype.indexOf
可能是最佳选择,如果它涉及速度问题.
eli*_*ocs 500
String.prototype.includes
ES6中有一个:
"potato".includes("to");
> true
Run Code Online (Sandbox Code Playgroud)
请注意,您可能需要加载String.prototype.includes
或类似才能在旧版浏览器上使用它.
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
Run Code Online (Sandbox Code Playgroud)
wz3*_*366 23
另一种选择是KMP(Knuth–Morris–Pratt)。
与单纯算法O(n?m)的最坏情况相比,KMP算法在最坏情况的O(n + m)时间中搜索长度为n的字符串中的长度为m的子字符串,因此使用KMP可能会如果您担心最坏的情况下的时间复杂度,则是合理的。
这是Nayuki项目的JavaScript实现,取自https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
Run Code Online (Sandbox Code Playgroud)
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5812445 次 |
最近记录: |