let str = 'Widget with id';
alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
alert( str.indexOf("id") ); // 1
There is an "id" inside "Widget"
Look closer to your string: "Widget with id" ๐
The first occurrence is found after "W..." which is the index of 1.
W ๐ 0
i ๐ 1 โ
d ๐ 2
g ๐ 3
e ๐ 4
t ๐ 5
If you would like to find the whole word, you can use a function something like this.
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