使用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 + "'");
}