it-swarm.cn

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

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

检查这个的合理方法是什么?

7434
gramm

ES6介绍 String.prototype.includes

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

string.includes(substring)

includes没有IE支持 。在ES5或更旧的环境中,可以使用 String.prototype.indexOf ,它在找不到子字符串时返回-1:

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

string.indexOf(substring) !== -1
12677
Fabien Ménager

ES6中有一个String.prototype.includes

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

请注意,此 在Internet Explorer或其他一些旧浏览器中不起作用 没有或不完整的ES6支持。为了使其在旧浏览器中工作,您可能希望使用像 Babel 这样的转换器,像 es6-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;
    }
  };
}
438
eliocs

另一种选择是 _ kmp _

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
8
wz366