includes()方法最直观,返回布尔值,区分大小写;2. indexOf()兼容性好,返回位置或-1;3. search()支持正则,适合忽略大小写;4. test()适合复杂模式匹配。推荐优先使用includes()。

javaScript中判断字符串是否包含某个字符或子字符串,有几种常用方法。下面介绍最实用且兼容性好的方式。
1. 使用 includes() 方法
includes() 是最直观的方法,用于判断字符串是否包含指定的子字符串,返回布尔值。
注意:该方法区分大小写。
示例:
const str = “Hello, world!”;
console.log(str.includes(“world”)); // true
console.log(str.includes(“World”)); // false(大小写敏感)
console.log(str.includes(“o”)); // true
2. 使用 indexOf() 方法
indexOf() 返回指定字符或子串首次出现的位置,若未找到则返回 -1。
通过判断返回值是否不等于 -1,即可知道是否包含。
示例:
const str = “Hello, world!”;
console.log(str.indexOf(“world”) !== -1); // true
console.log(str.indexOf(“xyz”) !== -1); // false
这个方法兼容性很好,适用于老版本浏览器。
3. 使用 search() 方法
search() 通常配合正则使用,返回匹配位置,未找到返回 -1。
示例:
const str = “Hello, world!”;
console.log(str.search(“world”) !== -1); // true
console.log(str.search(/WORLD/i) !== -1); // true(忽略大小写)
适合需要正则匹配的场景,比如忽略大小写或模糊匹配。
4. 使用正则 test() 方法
用 regexp 的 test() 方法判断字符串是否匹配特定模式。
示例:
const str = “Hello, world!”;
console.log(/world/.test(str)); // true
console.log(/World/i.test(str)); // true(i 表示忽略大小写)
适合复杂匹配逻辑,比如包含数字、特殊字符等。
基本上就这些。日常开发推荐优先使用 includes(),简洁清晰;需要忽略大小写或更灵活匹配时,可选 indexOf() 或正则方法。