javascript search



  1. Use regex to match key word
  2. use span class=highlight for the keywords, and define highlight in css
  3. add id , which will be used for anchor,  for every result
  4. when one result is selected, add attribute to that span so that the background change to red
  5. remove previous red and add bgColor to next result if selected
  6. if another search is requested, remove all the spans in the html body and go to step 1.
  • step 1:  s is the key word. var r=new RegExp(s,”gi”);  t=t.replace(r,”{searchHL}”+decode(s)+”{/searchHL}”)
  • step 2: var r=/{searchHL}(({(?!\/searchHL})|[^{])*){\/searchHL}/g;
    t=t.replace(r,”<span class=’highlight’>$1</span>”);
  • step 3: var keyNumber=1;
    var spans = document.getElementsByTagName(“span”);
    for (var i=0;i<spans.length;i++)
    { if(spans[i].className==”highlight”){
    spans[i].setAttribute(‘id’, ‘key’+keyNumber);
    keyNumber++; }  }
  • step 4 & 5 :function changeBgColor(id){
    var obj=document.getElementsByTagName(“body”)[0];
    //delete previous red
    var t=obj.innerHTML.replace(/ style=.?background-color: red.?.?”/gi,””);
    document.getElementById(id).style.backgroundColor = “red”;}
  • step 6:  t=obj.innerHTML.replace(/<span\s+class=.?highlight.? id=.?key.?.?.?>([^<>]*)<\/span>/gi,”$1″);

The step 6 costs a lot of time because different browser have different syntax of adding attribute. The regex has to exactly matching the content in the span, which is really time consuming because of having to  go to firebugs to check(windows IE use 开发人员工具F12)


. 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束

* 重复零次或更多次 + 重复一次或更多次 ? 重复零次或一次 {n} 重复n次 {n,} 重复n次或更多次 {n,m} 重复n到m次

红和蓝配合威力无穷,比如 .?代表:符号发送0或1次都匹配


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s