Use JS to highlight the key words in the article or search results

Source: Internet
Author: User

With JS to achieve, you can optimize the impact of efficiency, the use of server resources issues. The code is as follows:

The following is a reference fragment:
function Xp_highlight ()
{
This. KeyWords = null;

Formatting keywords
This.formatkeyword = function (content, keyword)
{
Keyword = keyword.replace (/(^\s*) | ( \s*$)/g, "");
if (keyword = = ")
return content;
var reg = new RegExp (' (' +keyword+ ') ', ' GI ');
Return Content.replace (Reg, ' <em>$1</em> ');
}

Redraw content Area
This.refreshcontent = function (ContentID)
{
var content = document.getElementById (ContentID). InnerHTML;
for (var i = 0; i < keywords.length i + +)
{
var strkey = keywords[i].tostring ();
var arrkey = Strkey.split (', ');
for (var j = 0; J < Arrkey.length; J + +)
{
var key = Arrkey[j];
Content = This.formatkeyword (content, key);
}
}
document.getElementById (contentid). InnerHTML = content;
}
}

Call Mode:

The
" Below is a reference fragment:
//  keyword definition
  &nbs p; var keywords = 
    [
         [' Arisisi, alixixi.com,,web development, really delicious, haha, hee '],
        [' dizzy brain swelling, Tired shortness of breath, uninteresting,,, toss, source download, CC, webmaster, programmer, Technology, development '],
        [' How, ah, yes, hello ']
    ];
    
    
    $ (document). Ready (function () {
        var hl = new xp_highlight ();
        hl.keywords = keywords; //  Here is the definition of the keyword
        hl.refreshcontent (' res '); //  here is the element ID number to format the content
&NBSP;&NBSP;&NBSP;&NBSP});   

CSS definition (you can set a variety of styles to support different types of keywords):

-->EM {font-size:small; color: #CC0033; font-style:normal;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.