Problem Overview
You want a single input that lets users find any word on the page and instantly see it highlighted, without server round‑trips or heavy libraries.
Core Idea: DOM Walk + Regex
The trick is to replace the page’s innerHTML with a version that wraps every match in a <span>. A global, case‑insensitive regular expression is the fastest way to locate all occurrences of the search term.
Implementation Steps
1. Grab the query from the input. 2. Build a RegExp: new RegExp('(' + escapeRegExp(query) + ')', 'gi'). 3. Replace body.innerHTML with the regex, inserting <span class="highlight">$1</span>. 4. Add a button listener to trigger the function. 5. Style .highlight with CSS to make the match obvious.
Full Code Example
/* CSS */
.highlight {
background: yellow;
color: black;
}
/* JavaScript */
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function highlight(text) {
if (!text) return;
var body = document.body;
var regex = new RegExp('(' + escapeRegExp(text) + ')', 'gi');
body.innerHTML = body.innerHTML.replace(regex, '<span class="highlight">$1</span>');
}
document.getElementById('searchBtn').addEventListener('click', function() {
var query = document.getElementById('q').value.trim();
if (query) {
highlight(query);
} else {
alert('Please enter a search term.');
}
});
Common Pitfalls & Enhancements
• Replacing innerHTML destroys event listeners; if your page has interactive elements, consider a tree walk instead. • The regex approach can mis‑highlight inside tags; for production, use a text‑node walker. • Debounce the input for instant search as the user types. • Add a clear button to remove all highlights.
Takeaway: A simple DOM walk with regex can turn any page into a searchable, highlightable document.
People also ask
Why does the highlight disappear after a page reload?
Because the replacement is only in memory; reloading resets the DOM. Persist the search term or re‑apply on load if needed.
Can I highlight multiple terms at once?
Yes—split the query by spaces, loop over each word, and apply the regex for each, or build a single regex with alternation (word1|word2).
Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.