通过正则表达式查找一个模式的所有实例
这个功能就是一般的文本查找功能,比较实用,记录下来,说不定以后可以用到
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>string的match用法</title> <style type="text/css"> #searchSubmit{ background-color: orange; width: 200px; text-align: center; padding: 10px; } .found{ background: red; } </style> </head> <body> <form id="textsearch"> <textarea id="incoming" cols="100" rows="10"></textarea> <p> Search pattern: <input id="pattern" type="text" /> </p> </form> <p id="searchSubmit">Search for pattern</p> <div id="searchResult"></div> </body> <script type="text/javascript"> window.onload = function(){ document.getElementById('searchSubmit').onclick = doSearch; } function doSearch(){ //获取模式 var pattern = document.getElementById('pattern').value; var re = new RegExp(pattern, 'g'); //获取字符串 var searchString = document.getElementById('incoming').value; //替换 var resultString = searchString.replace(re, "<span class='found'>$&</span>"); //插入到页面 document.getElementById('searchResult').innerHTML = resultString; } </script> </html>