Javascript开发

JS检查字符串包含某个字符的方法
贵鬼2025-02-19发布
154 0

使用includes方法:

let str = "Hello, world!";
let char = "w";
 
if (str.includes(char)) {
    console.log("字符串包含字符 '" + char + "'");
} else {
    console.log("字符串不包含字符 '" + char + "'");
}

使用indexOf方法:

let str = "Hello, world!";
let char = "w";
 
if (str.indexOf(char) !== -1) {
    console.log("字符串包含字符 '" + char + "'");
} else {
    console.log("字符串不包含字符 '" + char + "'");
}

使用正则表达式的test方法:

let str = "Hello, world!";
let char = "w";
let regex = new RegExp(char); // 或者使用 /w/ 创建正则表达式对象
 
if (regex.test(str)) {
    console.log("字符串包含字符 '" + char + "'");
} else {
    console.log("字符串不包含字符 '" + char + "'");
}

使用正则表达式的search方法:

let str = "Hello, world!";
let char = "w";
let regex = new RegExp(char); // 或者使用 /w/ 创建正则表达式对象
 
if (str.search(regex) !== -1) {
    console.log("字符串包含字符 '" + char + "'");
} else {
    console.log("字符串不包含字符 '" + char + "'");
}