【发布时间】:2022-12-30 09:06:52
【问题描述】:
通常我会期待一个 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
String.prototype.includes是区分大小写和is not supported by Internet Explorer没有polyfill。
在 ECMAScript 5 或更早的环境中,使用 String.prototype.indexOf,当找不到子字符串时返回 -1:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
【讨论】:
includes 执行 case-sensitive 搜索。
indexOf也是区分大小写的搜索,所以includes和indexOf都是区分大小写的。
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;
}
};
}
【讨论】:
number 的检查无法像 includes 那样执行。示例:es6 包含为"abc".includes("ab", "1") 返回 false 此 polyfill 将返回 true
另一种选择是KMP (Knuth–Morris–Pratt)。
KMP算法搜索长度-米子串的长度 -n最坏情况下的字符串 O(n+米) 时间,与 O(n⋅米) 对于朴素算法,因此如果您关心最坏情况下的时间复杂度,则使用 KMP 可能是合理的。
这是 Project 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[i] !== pattern[j])
j = lsp[j - 1];
if (pattern[i] === pattern[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[i] != pattern[j])
j = lsp[j - 1]; // Fall back in the pattern
if (text[i] == pattern[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] 以避免额外的函数调用,它可能会运行得更快。