【发布时间】:2010-12-19 21:12:07
【问题描述】:
通常我希望有一个String.contains() 方法,但似乎没有。
什么是合理的检查方法?
【问题讨论】:
标签: javascript string substring string-matching
通常我希望有一个String.contains() 方法,但似乎没有。
什么是合理的检查方法?
【问题讨论】:
标签: javascript string substring string-matching
ECMAScript 6 引入String.prototype.includes:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
includesdoesn’t have Internet Explorer support,不过。在 ECMAScript 5 或更早的环境中,使用 String.prototype.indexOf,当找不到子字符串时返回 -1:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
【讨论】:
includes 执行 case-sensitive 搜索。
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 这样的 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;
}
};
}
【讨论】:
number 的检查也无法像includes 那样执行。示例:es6 包含为 "abc".includes("ab", "1") 返回 false 这个 polyfill 将返回 true
另一种选择是KMP (Knuth–Morris–Pratt)。
KMP 算法在最坏情况下在长度为n的字符串中搜索长度为m的子字符串 O(n+m) 时间,与朴素算法的最坏情况 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
【讨论】:
includes 或indexOf 的地方实施KMP。 (虽然那些可能使用 KMP 的底层实现......不确定)
.charAt(i) 替换为[i] 以避免额外的函数调用,它可能会运行得更快。