Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created April 12, 2023 06:37
Show Gist options
  • Save DavidWells/6bbbbbd6f95a264fb4f7c6a70fc0fcd0 to your computer and use it in GitHub Desktop.
Save DavidWells/6bbbbbd6f95a264fb4f7c6a70fc0fcd0 to your computer and use it in GitHub Desktop.
Highlight text in a string of content
// Used to match HTML entities and HTML characters.
const unescapedHtml = /[&<>"']/g
const hasUnescapedHtml = RegExp(unescapedHtml.source)
const htmlEscapes = {
"&": "&amp",
"<": "&lt",
">": "&gt",
'"': "&quot",
"'": "&#39"
}
/* Converts the characters "&", "<", ">", '"', & "'" in `string` to their corresponding HTML entities */
function escapeString(str) {
return str && hasUnescapedHtml.test(str)
? str.replace(unescapedHtml, (character) => htmlEscapes[character])
: str
}
function highlightMatch(text, originalContent) {
var content = escapeString(originalContent)
var index = content.indexOf(text)
if (index >= 0) {
content =
content.substring(0, index) +
"<mark>" +
content.substring(index, index + text.length) +
"</mark>" +
content.substring(index + text.length)
return content
}
return originalContent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment