【问题标题】:How to check whether a string contains a substring in JavaScript?如何检查字符串是否包含 JavaScript 中的子字符串?
【发布时间】:2010-12-19 21:12:07
【问题描述】:

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

什么是合理的检查方法?

【问题讨论】:

    标签: javascript string substring string-matching


    【解决方案1】:

    ECMAScript 6 引入String.prototype.includes

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

    includesdoesn’t have Internet Explorer support,不过。在 ECMAScript 5 或更早的环境中,使用 String.prototype.indexOf,当找不到子字符串时返回 -1:

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

    【讨论】:

    • 虽然这是一个很好的答案,并且 OP 从未要求进行“区分大小写”的搜索,但应注意 includes 执行 case-sensitive 搜索。
    • 包括为空子字符串返回 true。
    • @Aashiq:是的,空字符串是每个字符串的子字符串。
    【解决方案2】:

    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 这样的 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;
        }
      };
    }
    

    【讨论】:

    • 只是好奇,为什么需要检查长度? IE 在那种情况下会失败吗?
    • number 的检查也无法像includes 那样执行。示例:es6 包含为 "abc".includes("ab", "1") 返回 false 这个 polyfill 将返回 true
    【解决方案3】:

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

    KMP 算法在最坏情况下在长度为n的字符串中搜索长度为m的子字符串 O(n+m) 时间,与朴素算法的最坏情况 O(nm) 相比,因此如果您关心的话,使用 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

    【讨论】:

    • 对这种方法没有任何疑问......但是为什么要在桌面上有includesindexOf 的地方实施KMP。 (虽然那些可能使用 KMP 的底层实现......不确定)
    • KMP 在这里提供线性 O(n) 性能。
    • @wz366 KMP 提供 O(n),其余的呢?有什么想法吗?
    • 如果这用于提高速度,如果您将.charAt(i) 替换为[i] 以避免额外的函数调用,它可能会运行得更快。
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 2013-05-18
    • 2021-12-30
    • 2022-12-30
    相关资源
    最近更新 更多