Find and Highlight Search Results

JavaScriptPosted on

For real-time search features, it’s nice feedback to highlight the matches to the given keywords. With this one-liner, it’s easy to find and wrap the results.

// Wrap the given keyword matches.
function highlight(text, keywords)
    return text.replace(new RegExp(keywords, 'gi'), '<span class="highlighted">$&</span>');
This solution works with one result at the same time. That means you need to run it on every result what you retrieved, for example from your back-end API.

Need a web developer? Maybe we can help, get in touch!

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in JavaScript category