Created
February 21, 2020 23:57
-
-
Save kendru/621a798c0179a67eb33e5d962e548923 to your computer and use it in GitHub Desktop.
Add case-insensitive non-overlapping highlights to text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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