如何在 JavaScript 中检查字符串是否包含子字符串?

时间:2022-11-07 16:49:56

如何在 JavaScript 中检查字符串是否包含子字符串?

// var test4 = _.includes(string, substring); 该方法需要此文件
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script type="text/javascript">
var string = "foo",
substring = "oo",
expr = /oo/; var test1 = string.includes(substring);
var test2 = string.indexOf(substring) !== -1;
var test3 = string.search(expr);
var test4 = _.includes(string, substring);
var test5 = expr.test(string);
var test6 = string.match(expr); console.log(test1); // true
console.log(test2); // true
console.log(test3); // 1
console.log(test4); // true
console.log(test5); // true
console.log(test6); // ["oo", index: 1, input: "foo"]
</script>

参考资料