Skip to content

Instantly share code, notes, and snippets.

@scottnunemacher
Created January 26, 2023 16:10
Show Gist options
  • Save scottnunemacher/f2169545ffbe0645bf93d87bcea26ba7 to your computer and use it in GitHub Desktop.
Save scottnunemacher/f2169545ffbe0645bf93d87bcea26ba7 to your computer and use it in GitHub Desktop.
JS - Highlight all matches to search input on Enter.
// 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