Created
January 26, 2023 16:10
-
-
Save scottnunemacher/f2169545ffbe0645bf93d87bcea26ba7 to your computer and use it in GitHub Desktop.
JS - Highlight all matches to search input on Enter.
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
// From: https://codingartistweb.com/2021/06/highlight-searched-text-with-javascript/ | |
function search() { | |
// Use the id of the input ex: text-to-search | |
let textToSearch = document.getElementById("text-to-search").value; | |
// Use the id of the source to be searched ex: paragraph | |
let paragraph = document.getElementById("paragraph"); | |
// Characters in search input to be escaped: [.*+?^${}()|[\]\\] | |
textToSearch = textToSearch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); | |
let pattern = new RegExp(`${textToSearch}`, "gi"); | |
paragraph.innerHTML = paragraph.textContent.replace(pattern, match => `<mark>${match}</mark>`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment