7417

通常我会期待一种String.contains()方法,但似乎没有。

什么是合理的检查方法?

4

3 回答 3

15103

ECMAScript 6 引入String.prototype.includes

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

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

includes 但是不支持 Internet Explorer。在 ECMAScript 5 或更早的环境中,使用String.prototype.indexOf,当找不到子字符串时返回 -1:

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

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

于 2009-11-24T13:05:36.550 回答
716

String.prototype.includesES6 中有一个

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

请注意,这在 Internet Explorer 或其他一些不支持或不支持 ES6 的旧浏览器中不起作用。为了让它在旧浏览器中工作,你可能希望使用像Babel这样的编译器,像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;
    }
  };
}
于 2013-01-07T10:23:16.590 回答
86

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

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

于 2017-07-05T22:26:38.857 回答