Answers:
ECMAScript 6引入了String.prototype.includes
:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring));
includes
但是不支持Internet Explorer。在ECMAScript 5或更旧的环境中,请使用String.prototype.indexOf
,当找不到子字符串时,它将返回-1:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1);
string.toUpperCase().includes(substring.toUpperCase())
/regexpattern/i.test(str)
> i标志代表不区分大小写
String.prototype.includes
ES6中有一个:
"potato".includes("to");
> true
请注意,这在Internet Explorer或其他不支持ES6或不完全支持ES6的旧浏览器中不起作用。为了使其在旧的浏览器中工作,您可能希望使用像Babel这样的编译器,像es6-shim这样的填充程序库,或MDN的这种polyfill:
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进行运行即可。
"boot".includes("T")
是false
另一种选择是KMP(Knuth–Morris–Pratt)。
的KMP算法搜索一个长度- 米的长度-串Ñ串在最坏情况下的O(Ñ + 米)时,相对于O(的最坏情况Ñ ⋅ 米)为幼稚算法,因此,使用可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
indexOf()
它是...