JavaScript indexOf() Method Explained
The indexOf() method in JavaScript is used to find the position of a specified substring within a string. It returns the index of the first matching substring, and if no match is found, it returns -1.
Grammar:
string.indexOf(searchValue[, fromIndex])
Parameters:
- searchValue: The substring you want to search for.
- fromIndex (optional): The index position to start the search from. If this parameter is omitted, the search will start from the beginning of the string.
Return value:
- Return the index of the first matching substring if found.
- If no matching substring is found, return -1.
I don’t have time to do all the laundry today.
I am too busy to finish all the laundry today.
const str = 'Hello, world!';
console.log(str.indexOf('world')); // 输出: 7
console.log(str.indexOf('World')); // 输出: -1,区分大小写
console.log(str.indexOf('o')); // 输出: 4,从索引位置4开始查找第一个匹配的子字符串
console.log(str.indexOf('o', 5)); // 输出: 8,从索引位置5开始查找第一个匹配的子字符串
console.log(str.indexOf('o', 20)); // 输出: -1,从索引位置20开始查找,超出字符串长度,没有找到匹配的子字符串
Please note that the indexOf() method is case-sensitive. If you need to perform a case-insensitive search, you can use the toLowerCase() or toUpperCase() method to convert the string to lowercase or uppercase before searching.