通常,我希望有一个String.contains()方法,但似乎并没有。
检查这一点的合理方法是什么?
发布于 2009-11-24 21:05:37
ECMAScript 6引入了String.prototype.includes
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
不过,includes doesn’t have Internet Explorer support。在ECMAScript 5或更早的环境中,请使用String.prototype.indexOf,当找不到子字符串时,它将返回-1:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
发布于 2013-01-07 18:23:17
There is a String.prototype.includes in ES6
"potato".includes("to");
> true请注意,此does not work in Internet Explorer or some other old browsers不支持ES6或支持不完整。要使其在旧浏览器中工作,您可能希望使用像Babel这样的转译器、像es6-shim这样的填充库,或者这个polyfill from MDN
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;
}
};
}发布于 2017-07-06 06:26:39
另一种选择是KMP (Knuth-Morris-Pratt)。
与朴素算法的O(n⋅m)时间相比,KMP算法在最坏情况下搜索长度为n的字符串的时间为O(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.
function kmpSearch(pattern, text) {
if (pattern.length == 0)
return 0; // Immediate match
// Compute longest suffix-prefix table
var lsp = [0]; // Base case
for (var i = 1; i < pattern.length; i++) {
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))
j = lsp[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
j++;
lsp.push(j);
}
// Walk through text string
var j = 0; // Number of chars matched in pattern
for (var i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j))
j = lsp[j - 1]; // Fall back in the pattern
if (text.charAt(i) == pattern.charAt(j)) {
j++; // Next char matched, increment position
if (j == pattern.length)
return i - (j - 1);
}
}
return -1; // Not found
}
console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false
https://stackoverflow.com/questions/1789945
复制相似问题