Set the search keyword to highlight the instance code:
Search keywords to highlight the status of the presentation is a more humane measures, such as Baidu or this site has such a function, can greatly improve the identification, the following code example through the introduction of how to achieve this function.
The code example is as follows:
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><Metaname= "Author"content= "http://www.softwhy.com/" /><title>Ant Tribe</title> <styletype= "Text/css">Strong{Color:Red} </style> <Scripttype= "Text/javascript">functionCreateexp (arry) {varStr=""; for(varI=0; I<Arry.length;i++) { if(i!=Arry.length-1) {str=Str+Arry[i]+"|"; } Else{str=Str+Arry[i]; } } return "("+Str+")";}functionHightkey (key,id) {vararr=NULL; varRegstr=NULL; varcontent=NULL; varReg=NULL; varnewcontent=NULL; varTheobj=document.getElementById (ID); Arr=Key.split (/\s+/); Regstr=Createexp (arr); Content=theobj.innerhtml; Reg=NewRegExp (REGSTR,"g"); returnnewcontent=content.replace (Reg,"<strong>$1</strong>");} Window.onload=function(){ varThediv=document.getElementById ("Thediv"); varKey="Ant Tribe Qingdao"; Thediv.innerhtml=Hightkey (Key,"Thediv");}</Script></Head> <Body> <DivID= "Thediv">Ant Tribe welcomes you, only efforts will have a good future, Ant tribe located in Qingdao South District</Div></Body> </HTML>
The above code implements our requirements, you can put the specified keywords in the string to highlight the form of the display, the following is a brief introduction to the implementation process.
I. Principle of implementation:
The principle is very simple, the final goal of the above code is to achieve the use of regular expressions to match each keyword, and then replace the matching keyword with the specified string, and then use CSS to highlight or bold, the principle is roughly the same, you can read the relevant reading, or post message.
Two. Related reading:
The 1.split () function can refer to the section of the Split () method of the JavaScript string object .
The 2.REGEXP () constructor can refer to the creation of a regular expression section.
The 3.replace () function can refer to the section of the regular expression replace () function .
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=10500
For more information, refer to: http://www.softwhy.com/javascript/
Set the search keyword to highlight instance code