Created
April 12, 2023 06:37
-
-
Save DavidWells/6bbbbbd6f95a264fb4f7c6a70fc0fcd0 to your computer and use it in GitHub Desktop.
Highlight text in a string of content
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
// Used to match HTML entities and HTML characters. | |
const unescapedHtml = /[&<>"']/g | |
const hasUnescapedHtml = RegExp(unescapedHtml.source) | |
const htmlEscapes = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': """, | |
"'": "'" | |
} | |
/* 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