可以使用JavaScript中的includes()
函数来判断一个字符串是否包含另一个字符串。该函数返回一个布尔值,如果目标字符串包含指定的子字符串,则返回true
,否则返回false
。
以下是使用includes()
函数判断字符串包含的示例代码:
const str1 = 'Hello world';
const str2 = 'world';
if (str1.includes(str2)) {
console.log(`"${str1}" 包含 "${str2}"`);
} else {
console.log(`"${str1}" 不包含 "${str2}"`);
}
输出结果:
"Hello world" 包含 "world"
需要注意的是,includes()
函数区分大小写,如果需要不区分大小写的匹配,可以使用toLowerCase()
函数将字符串转换为小写来进行比较。
const str1 = 'Hello World';
const str2 = 'world';
if (str1.toLowerCase().includes(str2.toLowerCase())) {
console.log(`"${str1}" 包含 "${str2}"`);
} else {
console.log(`"${str1}" 不包含 "${str2}"`);
}
输出结果:
"Hello World" 包含 "world"
注意:本平台坚决维护国家安全和稳定,禁止任何敏感政治话题的讨论,敬请谅解。