JavaScript中检查字符串是否包含子字符串的方法

JavaScript中检查字符串是否包含子字符串的方法

技术背景

在JavaScript编程中,经常会遇到需要检查一个字符串是否包含另一个子字符串的需求。然而,JavaScript本身一开始并没有像其他一些编程语言那样提供直接的String.contains()方法。不过,随着语言的发展和标准的更新,有了多种可行的解决方案。

实现步骤

1. 使用String.prototype.includes(ES6及以上)

ECMAScript 6引入了String.prototype.includes方法,它可以直接检查一个字符串是否包含另一个子字符串,并且返回一个布尔值。

2. 使用String.prototype.indexOf(ES5及更早版本)

在ES5或更旧的环境中,可以使用String.prototype.indexOf方法。该方法会返回子字符串在原字符串中首次出现的索引,如果未找到则返回 -1。

3. 使用KMP算法

KMP(Knuth–Morris–Pratt)算法是一种高效的字符串匹配算法,在处理大规模字符串匹配时,其时间复杂度优于朴素的匹配算法。

核心代码

使用String.prototype.includes

1
2
3
4
const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true

使用String.prototype.indexOf

1
2
3
4
var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1); // true

使用KMP算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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

最佳实践

  • ES6及以上环境:优先使用String.prototype.includes,因为它的语法简洁,代码可读性高。
  • ES5及更早环境:使用String.prototype.indexOf,这是兼容性最好的方法。
  • 处理大规模字符串匹配:如果对性能有较高要求,尤其是处理大规模字符串匹配时,可以考虑使用KMP算法。

常见问题

  • String.prototype.includes的兼容性问题String.prototype.includes不被Internet Explorer支持。如果需要在旧浏览器中使用,可以使用转译器(如Babel)、垫片库(如es6-shim)或MDN提供的polyfill:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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算法的复杂度:虽然KMP算法在最坏情况下的时间复杂度为O(n + m),优于朴素算法的O(n⋅m),但在大多数日常场景中,使用includesindexOf已经足够,实现KMP算法会增加代码的复杂度。除非对性能有极高要求,否则不建议使用。

JavaScript中检查字符串是否包含子字符串的方法
https://119291.xyz/posts/2025-04-16.javascript-string-substring-check/
作者
ww
发布于
2025年4月16日
许可协议