首页 > JavaScript > String.contains() 在JavaScript检查这一点的合理方法是什么?

String.contains() 在JavaScript检查这一点的合理方法是什么?

上一篇 下一篇

网友问题:

String.contains() 在JavaScript检查这一点的合理方法是什么?

分割线

网友回答:

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

分割线

网友回答:

ECMAScript 6 引入了:String.prototype.includes

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

console.log(string.includes(substring)); // true

String.prototype.includes区分大小写,如果没有 polyfill,Internet Explorer 不支持该大小写。

在 ECMAScript 5 或更早的环境中,使用 ,当找不到子字符串时返回 -1:String.prototype.indexOf

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

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

分割线

网友回答:

另一种选择是KMP(高德纳-莫里斯-普拉特)。

KMP 算法在最坏情况下 O(n+m) 时间搜索长度 n 字符串中的长度 m 子字符串,而朴素算法的最坏情况为 O(nm),因此如果您关心最坏情况的时间复杂度,使用 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[i] !== pattern[j])
      j = lsp[j - 1];
    if (pattern[i] === pattern[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[i] != pattern[j])
      j = lsp[j - 1]; // Fall back in the pattern
    if (text[i]  == pattern[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

模板简介:该模板名称为【String.contains() 在JavaScript检查这一点的合理方法是什么?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 892次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 编程语言
  • 文件大小 暂无信息
  • 上传时间 02-07
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
微信公众平台 html5 微信素材 微信模板 微信图片 响应式 企业网站 自适应 单页式简历模板 微信文章
您可能会喜欢的其他模板