js代码判断一个字符串里包含某个字符或者单词
可以使用 JavaScript 中的 indexOf() 方法来判断字符串中是否包含某个字符或单词。
判断字符串中是否包含某个字符:
const str = 'hello world';
if (str.indexOf('h') !== -1) {
console.log('字符串中包含字母 h');
}
判断字符串中是否包含某个单词:
const str = 'hello world';
if (str.indexOf('world') !== -1) {
console.log('字符串中包含单词 world');
}
如果想要忽略大小写进行匹配,可以将字符串和搜索关键字都转换为小写或大写字母:
const str = 'Hello World';
if (str.toLowerCase().indexOf('world') !== -1) {
console.log('字符串中包含单词 world');
}
注意,indexOf() 方法返回的是搜索关键字在字符串中第一次出现的位置,如果没有找到则返回 -1。因此,判断字符串中是否包含某个字符或单词时,需要检查返回值是否为 -1。
原文地址: https://www.cveoy.top/t/topic/NrY 著作权归作者所有。请勿转载和采集!