Explain Codes LogoExplain Codes Logo

Highlight a word with jQuery

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Sep 11, 2024
TLDR

Instantly highlight a specific word within text using jQuery by swapping the word with <span class="highlight">word</span>. Style the .highlight class in your CSS to make it stand out. Here's the code snippet:

$('p').html(function(_, html) { // swap/troll the word with "highlight" class return html.replace(/(\bword\b)/g, '<span class="highlight">$1</span>'); });

CSS:

.highlight { background-color: yellow; } /* Flashy yellow for the highlight - because it's 1980s again! */

Don't forget the \b delimiters around your word to target whole words only.

Understanding jQuery Highlight

jQuery's interaction with HTML to wrap items and dynamically apply styles possesses some key characteristics:

  • Whole word matching: \b in RegExp /\bword\b/g ensures complete words only. Prevents you from falling into the 'therapist' trap (figure it out!).
  • Casing: It's case-sensitive. 'Word' and 'word' are as different as cats and dogs! For case-insensitive option use RegExp with the 'i' flag, like /(\bword\b)/gi.
  • Personal touch: Element tags and class names can take on any guise that you desire. Like switching from Clark Kent (span) to Superman (div), or an outfit change ('.highlight' > '.emphasis')!

Multi-word Highlighting, Because Sometimes One is Not Enough

Need to highlight a sentence or a phrase? We've got you covered:

$('p').html(function(_, html) { // Ready for a spotlight? I sure am. return html.replace(/("the quick brown fox")/gi, '<span class="highlight">$1</span>'); });

This would highlight the same sequence in the text preserving the pristine nature of the phrase.

Cautious You Must Be, Code Jedi

Be aware that some jQuery plugins, including highlight plugins, may bear hidden scripts. Always fetch your plugins from trusted Jedi councils (repositories) and scrutinize their license and activities. Ensure it's an open-source license, like MIT, so that fellow Jedi can ensure its safety and improve its prowess.

Highlight's Over, Back to Normal

Post-highlight, you may wish to return to normalcy. Here is code to remove highlights:

function removeHighlights() { $('span.highlight').each(function() { // Who let the words out? They're escaping! $(this).replaceWith($(this).text()); }); } // Maybe return to the status quo? removeHighlights();

This function dutifully goes through span.highlight elements, replacing them with their original text, essentially erasing the highlight.

Party Time! Illuminate That Word!

Here's a more graphical portrayal of highlighting a word using jQuery:

Before we start: "The quick brown fox jumps over the lazy dog."

Set the spotlight (🔦):

$("p:contains('fox')").html(function(_, html) { // Look, it's a dancing fox! Wait, what? return html.replace(/(fox)/g, '<span class="highlight">$1</span>'); });

And voila!

"The quick brown 🔦fox🔦 jumps over the lazy dog."

Our 'fox' now stands out, shown in all its glory!

Advanced Scenarios: The Next Frontier

Handling Dynamic Content: In with the New

With dynamically generated content, time your call to the highlighting function to occur after the content loads or updates. You may use $(document).ajaxComplete() enable highlighting post-Ajax calls.

Search As You Go: Lights, Camera, Action!

Create an interactive search that highlights words as users type into the search field. Bind the highlighting function to the keyup event for a Hollywood-style instant text search.

Preprocessing Text: Makeover Time!

Some text may need a little grooming before the spotlight—normalize case sensitivity or strip diacritics to maintain consistency in search and prevent oddities in highlighting.