如何检查字符串是否包含JavaScript中的子字符串?

时间:2009-11-24 13:04:29

标签: javascript string substring string-matching

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

检查此问题的合理方法是什么?

3 个答案:

答案 0 :(得分:12728)

ES6介绍了String.prototype.includes

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

string.includes(substring)
但是,

includes doesn’t have IE support。在ES5或更旧版本的环境中,可以使用String.prototype.indexOf,它在找不到子字符串时返回-1:

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

string.indexOf(substring) !== -1

答案 1 :(得分:443)

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;
    }
  };
}

答案 2 :(得分:10)

另一种选择是KMP

KMP算法在最坏情况下的O( n + 长度 n 字符串中搜索长度 m 子字符串> m )时间,与天真算法的最坏情况O( n m )相比,所以如果你关心的话,使用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.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
}

使用示例:

kmpSearch('ays', 'haystack') != -1 // true
kmpSearch('asdf', 'haystack') != -1 // false