So given string geography and substring graph, we'd step it through like this:
gmatchesg, so j = 1edoes not matchr, so j = 0odoes not matchg, so j = 0gdoes matchg, so j = 1rdoes matchr, so j = 2adoes matcha, so j = 3 and so on...
At the same time, we also need to keep track of the actual index that the match starts. The j index will help us get the matching, but we need a idxOfStart variable for just the start.
Putting it all together:
xxxxxxxxxx21
let idxOfStart = 0;let j = 0;let str = 'digginn';let subStr = 'inn';​for (i = 0; i < str.length; i++) { // if match, compare next character of subStr with next of string if (str[i] == subStr[j]) { j++; } else { j = 0; }​ // keep track of where match starts and ends if (j == 0) { idxOfStart = i; } else if (j == subStr.length) { console.log(idxOfStart); // we know this is the start of match }}OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


