JavaScript implementation page keyword highlighting code _javascript tips

Source: Internet
Author: User
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title> keyword highlighting </title>
<body>
<div class= "Result" id= "TextBox" >
<p> Baidu (Nasdaq Abbreviation: BIDU) is the world's largest Chinese search engine, January 2000 by Li, Xu two people founded in Beijing Zhongguancun, is committed to providing people with "simple, reliable" </p>
<p> how to obtain information. "Baidu" two words from the Chinese Song Dynasty ci Xin Qiji's "Green Jade case" Yuan Xi "the words" the crowd seeks him thousand degrees ", symbolizes the Baidu to Chinese information retrieval technology's persistent pursuit. </p>
</div>
<script>
function Highlight (idval, keyword) {
var textbox = document.getElementById (Idval);
if ("" = = keyword) return;
Get all text content
var temp = textbox.innerhtml;
Console.log (temp);
var htmlreg = new RegExp ("\<.*?\>", "I");
var arr = new Array ();

Replace HTML tags
for (var i = 0; true; i++) {
Matching HTML tags
var tag = htmlreg.exec (temp);
if (tag) {
Arr[i] = tag;
} else {
Break
}
temp = Temp.replace (Tag, "{[+ i +")]} ";
}


Say keywords split into arrays
Words = decodeURIComponent (Keyword.replace (/\,/g, ')). Split (/\s+/);

Replace the keyword
for (w = 0; w < words.length; w++) {
Match keywords to retain special characters that can appear in keywords
var r = new RegExp ("(" + Words[w].replace (/[() {}.+*?^$|\\\[\]]/g, "\\$&") + ")", "IG");
temp = Temp.replace (R, "<b style= ' color:red; ') >$1</b> ");
}

Restore HTML tags
for (var i = 0; i < arr.length; i++) {
temp = Temp.replace ("{[(+ i + +")]} ", Arr[i]);
}
textbox.innerhtml = temp;
}
Highlight ("TextBox", "Baidu, Robin Li");
</script>
</body>

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.