Home > Web Front-end > JS Tutorial > How Can I Highlight a Specific Word within Text Using jQuery?

How Can I Highlight a Specific Word within Text Using jQuery?

Patricia Arquette
Release: 2024-12-07 20:40:16
Original
308 people have browsed it

How Can I Highlight a Specific Word within Text Using jQuery?

Highlight a Word with jQuery

Question:

Highlight a particular word in a text block. For example, highlight "dolor" in the following text:

<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
Copy after login

Expected Result:

<p>
    Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
    libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
Copy after login

jQuery Solution:

Yes, it is possible to achieve this effect using jQuery. The following code snippet provides a solution:

$.fn.highlight = function(word) {
  var pattern = word.replace(/[-[\]{}()*+?.,\^$|#\s]/g, "\$&amp;&quot;");
  return this.each(function() {
    $(this).html($(this).html().replace(new RegExp("(" + pattern + ")", "gi"), "<span class='highlight'>$&amp;</span>"));
  });
};

$("p").highlight("dolor");
Copy after login

Explanation:

  1. $.fn.highlight is a custom jQuery function that takes a word as a parameter.
  2. The pattern variable creates a regular expression pattern by escaping special characters in the word.
  3. The each function iterates over all matched elements (paragraph tags in this case) and replaces the occurrence of the word with a tag wrapped around it.
  4. Finally, the $("p").highlight("dolor") line calls the custom function, passing "dolor" as the word to be highlighted.

Note:

There are numerous other jQuery-based solutions and external plugins available, cater to specific needs and offer additional features. Explore these options to find the best fit for your requirements.

The above is the detailed content of How Can I Highlight a Specific Word within Text Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template