如何在javascript中检查字符串是否包含子字符串?

nwlqm0z1  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(349)

这个问题的答案是社区的努力。编辑现有答案以改进此帖子。它目前不接受新的答案或互动。

通常我会期待一个 String.contains() 方法,但似乎没有。
什么是合理的检查方法?

mu0hgdu0

mu0hgdu01#

介绍了ecmascript 6 String.prototype.includes :

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

console.log(string.includes(substring));
``` `includes` 但不支持internet explorer。在ecmascript 5或更早版本的环境中,使用 `String.prototype.indexOf` ,在找不到子字符串时返回-1:

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

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

rpppsulh

rpppsulh2#

有一个 String.prototype.includes 在es6中:

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

请注意,这在internet explorer或其他不支持es6或es6不完整的旧浏览器中不起作用。要使其在旧浏览器中工作,您可能希望使用诸如babel之类的transpiler、诸如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;
    }
  };
}
tyky79it

tyky79it3#

另一种选择是kmp(克努特-莫里斯-普拉特)。
kmp算法在最坏情况下的o(n+m)时间内搜索长度为n的字符串中的长度为m的子字符串,而在最坏情况下的o(n)时间内搜索长度为n的字符串⋅m) 对于naive算法,如果您关心最坏情况下的时间复杂度,那么使用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

相关问题