最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
js中indexof的用法
时间:2026-06-14 11:07:23 编辑:袖梨 来源:一聚教程网
JavaScript 中 indexOf() 用法
indexOf() 方法用于在字符串中查找指定的子字符串,并返回其第一个匹配项的索引位置。如果找不到子字符串,则返回 -1。
语法:
<code class="javascript">string.indexOf(substring[, startIndex])</code>
参数:
substring: 要查找的子字符串。startIndex(可选): 开始搜索的索引位置(从 0 开始)。用法:
<code class="javascript">let str = "Hello World";// 查找 "World" 的索引位置console.log(str.indexOf("World")); // 6// 从索引 2 开始查找console.log(str.indexOf("World", 2)); // -1// 查找不存在的子字符串console.log(str.indexOf("JavaScript")); // -1</code>特点:
它是区分大小写的。如果 startIndex 小于 0,则从字符串的开头开始搜索。如果 startIndex 大于字符串的长度,则返回 -1。如果子字符串为空字符串,则返回 0。示例:
<code class="javascript">// 查找字符串中第一个 "e" 的索引位置let str = "Elephant";let index = str.indexOf("e");// 如果找到子字符串,则打印其索引if (index !== -1) {console.log(`找到 "e" 的索引位置:${index}`);}</code>注意:
indexOf() 方法对 Unicode 字符串的支持有限。对于更复杂的字符串搜索,建议使用 search() 方法或正则表达式。
相关文章
- 九牧之野赵云反击枪阵容分享 06-19
- 混元大模型开发者版权风险:归属界定与使用限制 06-19
- 生存33天如何通关天怒模式 06-19
- 九牧之野许褚反击枪阵容推荐 06-19
- 九牧之野甄宓奶盾阵容推荐 06-19
- 九牧之野:新手开荒阵容推荐 06-19