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

JavaScript中判断字符串是否包含某个字符或子字符串,有几种常用方法。下面介绍最实用且兼容性好的方式。
includes() 是最直观的方法,用于判断字符串是否包含指定的子字符串,返回布尔值。
注意:该方法区分大小写。示例:
const str = "Hello, world!";
console.log(str.includes("world")); // true
console.log(str.includes("World")); // false(大小写敏感)
console.log(str.includes("o")); // true
indexOf() 返回指定字符或子串首次出现的位置,若未找到则返回 -1。
通过判断返回值是否不等于 -1,即可知道是否包含。
示例:
const str = "Hello, world!";
console.log(str.indexOf("world") !== -1); // true
console.log(str.indexOf("xyz") !== -1); // false
这个方法兼容性很好,适用于老版本浏览器。
search() 通常配合正则使用,返回匹配位置,未找到返回 -1。
示例:
const str = "Hello, world!";
console.log(str.search("world") !== -1); // true
console.log(str.search(/WORLD/i) !== -1); // true(忽略大小写)
适合需要正则匹配的场景,比如忽略大小写或模糊匹配。
用 RegExp 的 test() 方法判断字符串是否匹配特定模式。
示例:
const str = "Hello, world!";
console.log(/world/.test(str)); // true
console.log(/World/i.test(str)); // true(i 表示忽略大小写)
适合复杂匹配逻辑,比如包含数字、特殊字符等。
基本上就这些。日常开发推荐优先使用 includes(),简洁清晰;需要忽略大小写或更灵活匹配时,可选 indexOf() 或正则方法。
以上就是js判断字符串包含某个字符的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号