js 在字符串中查找子字符串
封面图
•
2025-11-24
•
JavaScript
280
0
0
0
在 JavaScript 中,你可以使用多种方法来查找字符串中的子字符串。以下是一些常用的方法: --- ### ✅ 1. `String.prototype.indexOf()` 返回子字符串在原字符串中第一次出现的索引,如果找不到则返回 `-1`。 ```javascript const str = "Hello, world!"; const substr = "world"; const index = str.indexOf(substr); console.log(index); // 输出: 7 ``` --- ### ✅ 2. `String.prototype.lastIndexOf()` 返回子字符串在原字符串中最后一次出现的索引,如果找不到则返回 `-1`。 ```javascript const str = "Hello, world! world!"; const substr = "world"; const lastIndex = str.lastIndexOf(substr); console.log(lastIndex); // 输出: 13 ``` --- ### ✅ 3. `String.prototype.includes()` 返回一个布尔值,表示是否包含指定的子字符串。 ```javascript const str = "Hello, world!"; const substr = "world"; const hasSubstring = str.includes(substr); console.log(hasSubstring); // 输出: true ``` --- ### ✅ 4. `String.prototype.startsWith()` 检查字符串是否以某个子字符串开头。 ```javascript const str = "Hello, world!"; const substr = "Hello"; const startsWith = str.startsWith(substr); console.log(startsWith); // 输出: true ``` --- ### ✅ 5. `String.prototype.endsWith()` 检查字符串是否以某个子字符串结尾。 ```javascript const str = "Hello, world!"; const substr = "world!"; const endsWith = str.endsWith(substr); console.log(endsWith); // 输出: true ``` --- ### ✅ 6. `String.prototype.search()` 使用正则表达式来查找子字符串,返回第一个匹配的索引。 ```javascript const str = "Hello, world!"; const substr = /world/; const index = str.search(substr); console.log(index); // 输出: 7 ``` --- ### ✅ 7. `String.prototype.match()` 使用正则表达式来查找所有匹配项(返回数组)。 ```javascript const str = "Hello, world! Hello again."; const substr = /Hello/g; const matches = str.match(substr); console.log(matches); // 输出: ["Hello", "Hello"] ``` --- ### 📌 总结 | 方法 | 返回值 | 是否区分大小写 | |------|--------|----------------| | `indexOf()` | 索引 | 是 | | `lastIndexOf()` | 索引 | 是 | | `includes()` | 布尔 | 是 | | `startsWith()` | 布尔 | 是 | | `endsWith()` | 布尔 | 是 | | `search()` | 索引 | 是 | | `match()` | 数组 | 是 | --- 如果你需要**不区分大小写**的查找,可以使用正则表达式并加上 `i` 标志,例如: ```javascript str.match(/hello/i); ``` --- 如需更复杂的匹配(如正则、多行等),也可以使用 `RegExp` 对象进行操作。欢迎继续提问!
上一篇:
Android 内容提供者组件根据请求从一个应用程序向其他应用程序提供数据
下一篇:
Android - Intents and Filters教程
标题录入,一次不能超过6条
留言
评论