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