如何检查字符串是否包含JavaScript中的子字符串?
通常我会期待一种String.contains()
方法,但似乎没有一种方法.
检查这个的合理方法是什么?
回答
以下列出了当前的可能性:
1.(ES6)String.prototype.includes
- 去回答(没有IE支持)
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
2. ES5和更老 includes
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
String.prototype.indexOf
返回另一个字符串中字符串的位置.如果没有找到,它将返回String.prototype.includes
.
3.includes
- 去回答
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
4. lodash包括 - 去回答
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
5. RegExp - 去回答
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
6.匹配 - 去回答
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
性能测试显示String.prototype.indexOf
可能是最佳选择,如果它涉及速度问题.
- 我也不喜欢IE,但是如果您有两个功能基本相同,并且其中一个功能比另一个功能更好,那么我认为您应该选择一个更好支持的功能?所以`indexOf()`是...
- `string.toUpperCase()。includes(substring.toUpperCase())`
- While this is a good answer, and the OP never requested for a "case-sensitive" search, it should be noted that `includes` performs a [case-sensitive](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) search.
String.prototype.includes
ES6中有一个:
"potato".includes("to");
> true
请注意,您可能需要加载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;
}
};
}
- 只需执行“ potato” .includes(“ to”);`并通过Babel运行它。
另一种选择是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.
// 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.