Created
September 10, 2021 20:01
-
-
Save DavidWells/6028e3e1ab4a43b15da9e82714a38ab9 to your computer and use it in GitHub Desktop.
Highlight Search match in JS
This file contains hidden or 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 highlightMatch(string, regexp) { | |
return escapeString(string).replace(regexp, (match) => `<mark>${match}</mark>`) | |
} | |
// 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; | |
} | |
const content = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. | |
Integer vitae mauris arcu, eu pretium nisi. Praesent fringilla ornare ullamcorper. | |
Pellentesque diam orci, sodales in blandit ut, placerat quis felis. | |
Vestibulum at sem massa, in tempus nisi. Vivamus ut fermentum odio. Etiam porttitor faucibus volutpat. | |
Vivamus vitae mi ligula, non hendrerit urna. Suspendisse potenti. Quisque eget massa a massa semper mollis.` | |
const searchWord = 'orci' | |
console.log(highlightMatch(content, new RegExp(searchWord, "gi"))) | |
/* | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit. | |
Integer vitae mauris arcu, eu pretium nisi. Praesent fringilla ornare ullamcorper. | |
Pellentesque diam <mark>orci</mark>, sodales in blandit ut, placerat quis felis. | |
Vestibulum at sem massa, in tempus nisi. Vivamus ut fermentum odio. Etiam porttitor faucibus volutpat. | |
Vivamus vitae mi ligula, non hendrerit urna. Suspendisse potenti. Quisque eget massa a massa semper mollis. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment