Home > Web Front-end > JS Tutorial > JavaScript code to highlight text

JavaScript code to highlight text

php中世界最好的语言
Release: 2018-03-16 16:17:07
Original
2325 people have browsed it

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], &#39;g&#39;);    if (re.test(text)) {
      text = text.replace(re, &#39;<&#39;+ tag +&#39; class="highlight">$&</&#39;+ tag +&#39;>&#39;);
    }
  } 
  return text;
}
Copy after login

You will also need to cancel the highlighted function:

function unhighlight(text, tag) {  // Default tag if no tag is provided
  tag = tag || &#39;span&#39;;  var re = new RegExp(&#39;(<&#39;+ tag +&#39;.+?>|<\/&#39;+ tag +&#39;>)&#39;, &#39;g&#39;);  return text.replace(re, &#39;&#39;);
}
Copy after login

How to use:

$(&#39;p&#39;).html( highlight(
    $(&#39;p&#39;).html(), // the text
    [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;hello world&#39;], // list of words or phrases to highlight
    &#39;strong&#39; // custom tag));
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template