// 判断字符串是否包含某个子字符串的方法
// 使用 includes() 方法
let str = "Hello, world!";
if (str.includes("world")) {
console.log("包含 'world' 字符串");
} else {
console.log("不包含 'world' 字符串");
}
// 使用 indexOf() 方法
if (str.indexOf("world") !== -1) {
console.log("包含 'world' 字符串");
} else {
console.log("不包含 'world' 字符串");
}
// 使用 search() 方法
if (str.search("world") !== -1) {
console.log("包含 'world' 字符串");
} else {
console.log("不包含 'world' 字符串");
}
// 使用正则表达式
let regex = /world/;
if (regex.test(str)) {
console.log("包含 'world' 字符串");
} else {
console.log("不包含 'world' 字符串");
}
-1
。indexOf()
类似,但它可以接受正则表达式作为参数。test()
方法来检查字符串是否匹配给定的正则表达式模式。上一篇:js callback
下一篇:js 判断字符串包含
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站