通常我希望有一个 String.contains()
方法,但似乎没有。
什么是合理的检查方法?
最佳答案
引入了 ECMAScript 6 String.prototype.includes
:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
String.prototype.includes
区分大小写和is not supported by Internet Explorer没有 polyfill .
在 ECMAScript 5 或更早的环境中,使用 String.prototype.indexOf
,当找不到子字符串时返回-1:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
关于javascript - 如何检查字符串是否包含 JavaScript 中的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789945/