JavaScript 中的 indexOf() 方法用于在字符串中查找指定的子字符串,并返回其起始索引。如果未找到子字符串,则返回 -1。其语法为 string.indexOf(substring[, startIndex]),参数包含要查找的子字符串和可选的起始索引。该方法区分大小写,支持正向搜索,适用于区分不同字符串的场景。

JavaScript 中 indexOf() 用法
indexOf() 方法用于在字符串中查找指定的子字符串,并返回其第一个匹配项的索引位置。如果找不到子字符串,则返回 -1。
语法:
<code class="javascript">string.indexOf(substring[, startIndex])</code>
参数:
用法:
<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>特点:
示例:
<code class="javascript">// 查找字符串中第一个 "e" 的索引位置
let str = "Elephant";
let index = str.indexOf("e");
// 如果找到子字符串,则打印其索引
if (index !== -1) {
console.log(`找到 "e" 的索引位置:${index}`);
}</code>注意:
indexOf() 方法对 Unicode 字符串的支持有限。对于更复杂的字符串搜索,建议使用 search() 方法或正则表达式。
以上就是js中indexof用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号