So given string geography
and substring graph
, we'd step it through like this:
g
matchesg
, so j = 1e
does not matchr
, so j = 0o
does not matchg
, so j = 0g
does matchg
, so j = 1r
does matchr
, so j = 2a
does 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:
xxxxxxxxxx
21
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