Home > Article > Web Front-end > JavaScript code to highlight text
This time I will bring you the JavaScript code to highlight text. What are the precautions for using JavaScript to highlight text? The following is a practical case. Let’s take a look. one time.
There are many JQuery third-party libraries that can implement the function of highlighting text, but I prefer to use the following small piece of JavaScript code to achieve this function. It It is very short and can be flexibly modified according to my needs, and I can define the highlight style myself. The following two functions can help you create your own text highlighting plug-in.
function highlight(text, words, tag) { // Default tag if no tag is provided tag = tag || 'span'; var i, len = words.length, re; for (i = 0; i < len; i++) { // Global regex to highlight all matches re = new RegExp(words[i], 'g'); if (re.test(text)) { text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>'); } } return text; }
You will also need to cancel the highlighted function:
function unhighlight(text, tag) { // Default tag if no tag is provided tag = tag || 'span'; var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g'); return text.replace(re, ''); }
How to use:
$('p').html( highlight( $('p').html(), // the text ['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight 'strong' // custom tag));
I believe you have mastered the method after reading the case in this article. Please pay attention for more exciting things. php Chinese websiteOther related articles!
Recommended reading:
JavaScript code snippet to determine whether a date is valid
Detailed explanation of Event Loop of Node.js
Task Queue of JavaScript Running Mechanism
#How to prevent the form page in django from automatically submitting after refreshing
The above is the detailed content of JavaScript code to highlight text. For more information, please follow other related articles on the PHP Chinese website!