【问题标题】:How to check whether a string contains a substring in JavaScript?如何检查一个字符串是否包含 JavaScript 中的子字符串?
【发布时间】:2022-12-30 09:06:52
【问题描述】:

通常我会期待一个 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

    String.prototype.includes区分大小写is not supported by Internet Explorer没有polyfill

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

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

    【讨论】:

    • 虽然这是一个很好的答案,而且 OP 从未要求进行“区分大小写”的搜索,但应该注意 includes 执行 case-sensitive 搜索。
    • @Aashiq:是的,空字符串是每个字符串的子字符串。
    • @Gavin 默认情况下,如果我想知道某物是否是子字符串,我想它会区分大小写。毕竟,“A”和“a”是不同的字符。 OP 从未请求过“不区分大小写”的搜索(如果您将所有内容都设为小写,这是一个简单的解决方案)
    • indexOf也是区分大小写的搜索,所以includesindexOf都是区分大小写的。
    • 为什么要在这里讨论区分大小写?
    【解决方案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这样的垫片库,或者这个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最坏情况下的字符串 O(n+) 时间,与 O(n) 对于朴素算法,因此如果您关心最坏情况下的时间复杂度,则使用 KMP 可能是合理的。

    这是 Project 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[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

    【讨论】:

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