let str = 'As sly as a fox, as strong as an ox';let target = 'as'; // let's look for itlet pos = 0;while (true) { let foundPos = str.indexOf(target, pos); if (foundPos == -1) break; alert( `Found at ${foundPos}` ); pos = foundPos + 1; // continue the search from the next position}
The same algorithm can be layed out shorter:
let str = "As sly as a fox, as strong as an ox";let target = "as";let pos = -1;while ((pos = str.indexOf(target, pos + 1)) != -1) { alert( pos );}