问题描述
在JavaScript中,如何判断一个字符串是否包含另外一个子字符串,比如:'foo'
是否包含'oo'
?
解决方案
在ES6中,建议使用String.prototype.includes
:
var string = "foo",
substring = "oo";
string.includes(substring)
然而,IE浏览器不支持includes
方法,所以,在ES5或者老版本浏览器中,我们使用String.prototype.indexOf
方法代替,该方法在没有查找到子串的情况下返回-1
:
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1