js 判断字符串是否包含某字符串,String对象中查找子字符
2025-09-19 22:24
JavaScript
225
0
0
0
标题录入
封面图
在 JavaScript 中,判断一个字符串是否包含另一个子字符串,可以使用以下几种方法: --- ### ✅ 方法一:`String.prototype.includes()` 这是最推荐的方式,语法清晰、语义明确。 ```javascript const str = "Hello, world!"; const substring = "world"; if (str.includes(substring)) { console.log("包含子字符串"); } else { console.log("不包含子字符串"); } ``` **优点**: - 简洁易读 - 支持 ES6 及以上版本 --- ### ✅ 方法二:`String.prototype.indexOf()` 通过查找子字符串的索引,如果返回 `-1` 表示没有找到。 ```javascript const str = "Hello, world!"; const substring = "world"; if (str.indexOf(substring) !== -1) { console.log("包含子字符串"); } else { console.log("不包含子字符串"); } ``` **优点**: - 兼容性好(支持所有浏览器) --- ### ✅ 方法三:`String.prototype.search()` 使用正则表达式进行匹配,也可以用于查找子字符串。 ```javascript const str = "Hello, world!"; const substring = "world"; if (str.search(substring) !== -1) { console.log("包含子字符串"); } else { console.log("不包含子字符串"); } ``` > 注意:`search()` 是基于正则表达式的,如果你只是想查找普通字符串,建议用 `includes()` 或 `indexOf()` 更安全。 --- ### ✅ 方法四:`String.prototype.match()` 配合正则表达式来判断是否存在子字符串。 ```javascript const str = "Hello, world!"; const substring = "world"; if (str.match(substring)) { console.log("包含子字符串"); } else { console.log("不包含子字符串"); } ``` > 这种方式也依赖于正则表达式,如果子字符串中有特殊字符(如 `.`、`*` 等),需要转义。 --- ## 总结对比 | 方法 | 是否推荐 | 是否支持 ES6 | 是否使用正则 | |--------------------|----------|----------------|----------------| | `includes()` | ✅ | ✅ | ❌ | | `indexOf()` | ✅ | ✅ | ❌ | | `search()` | ⚠️ | ✅ | ✅ | | `match()` | ⚠️ | ✅ | ✅ | --- 如果你只是要判断是否包含某个子字符串,推荐使用 `includes()` 方法。
上一篇:
JavaScript 经典实例日常收集整理常用经典 6
下一篇:
用js使得输入框input只能输入数字
标题录入,一次不能超过6条
墨菲定律
T:0.006069s,M:117.54 KB
返回顶部
留言
留言
评论