Display where a substring is used in a string
const highlightPattern = (str, pattern) => {
let onlyRepeatedStr = '';
let lastMatchIndex = -1;
const spaces = (n) => new Array(n).fill('-').join('');
while ((lastMatchIndex = str.indexOf(pattern, lastMatchIndex)) >= 0) {
onlyRepeatedStr += spaces(lastMatchIndex - onlyRepeatedStr.length) + pattern;
// shift the beginning of the next loop .indexOf
lastMatchIndex += pattern.length;
}
onlyRepeatedStr += spaces(str.length - onlyRepeatedStr.length);
console.log(str);
console.log(onlyRepeatedStr);
};
highlightPattern("AAAAAAbAAAAb", "b")
// Output:
// AAAAAAbAAAAb
// ------b----b