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

const string = "foo";
const substring = "oo";

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

使用String.prototype.indexOf

var string = "foo";
var substring = "oo";

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

使用KMP算法

// 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:
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算法会增加代码的复杂度。除非对性能有极高要求,否则不建议使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1010n111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值