<!doctype html> <html> <head> <meta charset="utf-8"> <title>拆分字符串,存入数组</title> <style> *{ padding:0; margin:0; } </style> </head> <body> <form id="textsearch"> <textarea id="incoming" cols="150" rows="10"></textarea> <p>Search pattern:<input id="pattern" type="text"></p> </form> <button id="searchSubmit">Search for pattern</button> <div id="searchResult"></div> <script type="text/javascript"> var copy=document.getElementById("searchResult"); var button=document.getElementById("searchSubmit"); var str=""; button.onclick=function(){ content=document.getElementById("incoming").value; var search=document.getElementById("pattern").value; var re=new RegExp(search,"g"); var result,str="",first=0,last; while((result=re.exec(content))!=null){ last=result.index; str+=content.substring(first,last)+"<span id=mark style='background-color:yellow;'>" +result[0] +"</span>" first=re.lastIndex; } str+=content.substring(first,content.length);//注意最后一次匹配之后的字符串要加上,字符串起始位置为first. copy.innerHTML=str; }; </script> </body> </html>
除了这个方法外,还能使用更简单的replace()方法:
<script type="text/javascript"> var copy=document.getElementById("searchResult"); var button=document.getElementById("searchSubmit"); button.onclick=function(){ content=document.getElementById("incoming").value; var search=document.getElementById("pattern").value; var re=new RegExp(search,"g"); var result=content.replace(re,"<span style='background-color:yellow;'>$&</span>"); copy.innerHTML=result; }; </script>
Remark:
Pattern Purpose $$ Allows a literal dollar sign ($) in replacement $& Inserts matched substring $` Inserts portion of string before match $' Inserts portion of string after match $n Inserts n th captured parenthetical value when using RegExp
1.6 查找指定字符串,并高亮显示 p21
最新推荐文章于 2022-06-30 17:27:04 发布