如何检查一个字符串是否包含子字符串的JavaScript方法?

发布时间 2023-10-06 12:54:42作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=如何检查一个字符串是否包含子字符串的JavaScript方法?

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

有什么合理的方式来检查这个吗?


ECMAScript 6引入了String.prototype.includes

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

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

String.prototype.includes是区分大小写的,并且在Internet Explorer中不支持(在https://caniuse.com/#feat=es6-string-includes上查看),除非使用polyfill(在https://github.com/zloirock/core-js/blob/master/packages/core-js/modules/es.string.includes.js上查看)。

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

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

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