如何在JavaScript中检查字符串是否包含子字符串?

通常我希望有一个String.contains()方法,但似乎没有。

有什么合理的方法来检查这一点?

7469048 次浏览

ECMAScript 6引入了#0

const string = "foo";const substring = "oo";
console.log(string.includes(substring)); // true

String.prototype.includes区分大小写Internet Explorer不支持没有聚填充

在ECMAScript 5或更早的环境中,使用#0,当找不到子字符串时返回-1:

var string = "foo";var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true

在ES6中有一个#0

"potato".includes("to");> true

请注意,这个不适用于Internet Explorer或其他旧浏览器没有或不完整的ES6支持。要使其在旧浏览器中工作,您可能希望使用像巴别塔这样的转译器、像es6-shim这样的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;}};}

另一种选择是KMP(Knuth-Morris-Pratt)。

KMP算法在最坏情况下O(n+m)时间在长度n字符串中搜索长度m子字符串,而对于朴素算法,最坏情况为O(nm),因此如果您关心最坏情况时间复杂度,使用KMP可能是合理的。

以下是奈雪的茶项目的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 tablevar lsp = [0]; // Base casefor (var i = 1; i < pattern.length; i++) {var j = lsp[i - 1]; // Start by assuming we're extending the previous LSPwhile (j > 0 && pattern[i] !== pattern[j])j = lsp[j - 1];if (pattern[i] === pattern[j])j++;lsp.push(j);}
// Walk through text stringvar j = 0; // Number of chars matched in patternfor (var i = 0; i < text.length; i++) {while (j > 0 && text[i] != pattern[j])j = lsp[j - 1]; // Fall back in the patternif (text[i]  == pattern[j]) {j++; // Next char matched, increment positionif (j == pattern.length)return i - (j - 1);}}return -1; // Not found}
console.log(kmpSearch('ays', 'haystack') != -1) // trueconsole.log(kmpSearch('asdf', 'haystack') != -1) // false