在JavaScript中,我们可以使用经典的indexOf()
或新的ES6 includes
来检查String是否包含子字符串。
// old school, classic way
var str = "mkyong";
if (str.indexOf('yo') > -1) { // returns `-1` if it is not present.
console.log('match') // display this
} else {
console.log('not found')
}
// ES6 only
var str = "mkyong";
console.log(str.includes('mk')); //true
console.log(str.includes('mkg'));//false
参考文献
标签: JavaScript 字符串
翻译自: https://mkyong.com/javascript/javascript-check-if-string-contains-a-substring/