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>
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>
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, "\$&""); return this.each(function() { $(this).html($(this).html().replace(new RegExp("(" + pattern + ")", "gi"), "<span class='highlight'>$&</span>")); }); }; $("p").highlight("dolor");
Explanation:
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!