JavaScript indexOf() 方法:查找字符串中的子字符串
JavaScript 的 indexOf() 方法用于查找字符串内指定子字符串的位置。如果找到了该子字符串,则返回第一个匹配项的索引;如果未找到该子字符串,则返回 -1。
语法:
str.indexOf(searchValue[, fromIndex])
参数:
- searchValue:要查找的子字符串。
- fromIndex:可选,从该索引位置开始查找。默认值为 0。
使用示例:
var str = 'Hello World!';
console.log(str.indexOf('World')); // 输出 6
console.log(str.indexOf('WORLD')); // 输出 -1,未找到匹配项
注意事项:
- indexOf() 方法区分大小写。
- 如果要搜索的子字符串在字符串中出现多次,indexOf() 方法将始终返回第一个匹配项的索引。
- 如果要查找的子字符串为空字符串 (''),则 indexOf() 方法将始终返回 0。
原文地址: https://www.cveoy.top/t/topic/n51B 著作权归作者所有。请勿转载和采集!