let str='Widget with id';
alert(str.indexOf('Widget'));//0,因为在的开头找到了"Widget">
alert(str.indexOf('widget'));//-1,未找到,搜索区分大小写
alert(str.indexOf("id"));//1
有一个"id";内部";"小部件";
仔细查看您的字符串:"Wid获得id";
第一次出现是在";W…";这是1的索引。
W 0
i 1✅
d 2
g 3
e 4
t 5
如果你想找到整个单词,你可以使用这样的函数。
- 将字符串分成一个数组
- 遍历数组
- 将每个单词更改为一个字符数组
- 遍历chars数组并保持每个字母的运行计数
- 在每个单词后面加一,以计算空格
- 找到单词后停止迭代
let str = 'Widget with id';
function findIndexOfWholeWord(str, searchStr){
const words = str.split(' ')
let numOfChars = 0
for(let word of words){
if(word === searchStr) break
word.split('').forEach(char=>numOfChars++)
numOfChars++
}
return numOfChars
}
console.log(findIndexOfWholeWord(str,'id')) //12