JavaScript 中如何检查字符串是否包含子字符串? [英] How to check whether a string contains a substring in JavaScript?
本文介绍了JavaScript 中如何检查字符串是否包含子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常我希望有一个 String.contains()
方法,但似乎没有.
Usually I would expect a String.contains()
method, but there doesn't seem to be one.
什么是合理的检查方法?
What is a reasonable way to check for this?
推荐答案
ECMAScript 6 引入 String.prototype.includes
:
ECMAScript 6 introduced String.prototype.includes
:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
includes
没有 Internet Explorer 支持, 尽管.在 ECMAScript 5 或更早的环境中,使用 String.prototype.indexOf
,当找不到子串时返回-1:
includes
doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf
, which returns -1 when a substring cannot be found:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
这篇关于JavaScript 中如何检查字符串是否包含子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文