Skip to content

Instantly share code, notes, and snippets.

@kendru
Created February 21, 2020 23:57
Show Gist options
  • Save kendru/621a798c0179a67eb33e5d962e548923 to your computer and use it in GitHub Desktop.
Save kendru/621a798c0179a67eb33e5d962e548923 to your computer and use it in GitHub Desktop.
Add case-insensitive non-overlapping highlights to text
function highlightText(text, highlights) {
const lcText = text.toLowerCase();
highlights = highlights.map(h => h.toLowerCase());
let addedChars = 0;
for (let i = 0; i < text.length; i++) {
for (const highlight of highlights) {
if (
lcText[i] === highlight[0] &&
lcText.substring(i, i + highlight.length) === highlight
) {
const startIdx = i + addedChars;
const endIdx = startIdx + highlight.length;
const preHighlight = text.substring(0, startIdx);
const highlighted = text.substring(startIdx, endIdx);
const postHighlight = text.substring(endIdx);
text = `${preHighlight}<b>${highlighted}</b>${postHighlight}`;
addedChars += 7;
i += highlight.length;
}
}
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment