The indexOf() method in JavaScript is used to find a specified substring in a string and return its starting index. If the substring is not found, -1 is returned. The syntax is string.indexOf(substring[, startIndex]), and the parameters include the substring to be found and an optional starting index. This method is case-sensitive, supports forward search, and is suitable for scenarios where different strings are distinguished.
##indexOf() Usage in JavaScript
indexOf() Method is used to find the specified substring in a string and return the index position of its first match. If the substring is not found, -1 is returned.
Syntax:
<code class="javascript">string.indexOf(substring[, startIndex])</code>
Parameters:
Usage:
<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>
Features:
Example:
<code class="javascript">// 查找字符串中第一个 "e" 的索引位置 let str = "Elephant"; let index = str.indexOf("e"); // 如果找到子字符串,则打印其索引 if (index !== -1) { console.log(`找到 "e" 的索引位置:${index}`); }</code>
Note:
indexOf() method for Unicode String support is limited. For more complex string searches, it is recommended to use the
search() method or regular expressions.
The above is the detailed content of Indexof usage in js. For more information, please follow other related articles on the PHP Chinese website!