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


Answers:


13769

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


25
我也不喜欢IE,但是如果您有两个功能基本相同,并且其中一个功能比另一个功能更好,那么我认为您应该选择一个更好支持的功能?所以indexOf()它是...
rob74

3
是否可以进行不区分大小写的搜索?
Eric McWinNEr

18
string.toUpperCase().includes(substring.toUpperCase())
罗德里戈·平托

2
@EricMcWinNEr- /regexpattern/i.test(str)> i标志代表不区分大小写
Code Maniac

在Google App脚本中,这似乎不适用于我。
瑞安

559

String.prototype.includesES6中有一个

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

请注意,这在Internet Explorer或其他不支持ES6或不完全支持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;
    }
  };
}

3
只需"potato".includes("to");通过Babel进行运行即可。
Derk Jan Speelman,

1
包括不支持IE可悲
甜寒冷费城

@eliocs您可以回答这个问题吗?我收到任何一条消息。需要改变的消息stackoverflow.com/questions/61273744/...
sejn

1
它的另一个优点是也区分大小写。"boot".includes("T")false
Jonatas CD

47

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

的KMP算法搜索一个长度- 的长度-串Ñ串在最坏情况下的O(Ñ + )时,相对于O(的最坏情况Ñ)为幼稚算法,因此,使用可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


11
这虽然
矫kill过
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.