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

82 浏览
0 Comments

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

这个问题的答案是一个社区共同努力。编辑现有答案以改善此帖子。目前不接受新答案或交互。

通常我会期望有一个String.contains()方法,但好像没有。有没有一个合理的方法来检查这个?

admin 更改状态以发布 2023年5月20日
0
0 Comments

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

0
0 Comments

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 或更早的环境中,请使用 String.prototype.indexOf,它会在子字符串未找到时返回 -1:

var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true

0