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

2020/09/13 12:56 · javascript ·  · 0评论

通常我希望有一种String.contains()方法,但是似乎没有。

有什么合理的方法来检查?

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

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

另一种选择是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
本文地址:http://javascript.askforanswer.com/ruhejianchazifuchuanzaijavascriptzhongshifoubaohanzizifuchuan.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!