<!doctype html> <html> <head> <meta charset="utf-8"> <title>拆分字符串,存入数组</title> <style> *{ padding:0; margin:0; } #Flist{ font:18px arial,Sans-Serif; } </style> </head> <body> <h1 id="fruit">Now is the time and this is the time and that is the time</h1> <div id="Flist"></div> <script type="text/javascript"> var content=document.getElementById("fruit").lastChild.nodeValue; var re=new RegExp("t\\w*e","g"); var result,str=""; //此处result不能提前赋值result=re.exec(content),然后来直接判断result是否为null,否则在循环体中每次都会作为一个新实例从0开始匹配,永远返回true,然后陷入无限循环。 while((result=re.exec(content))!=null){ str+="at "+result.index+" we found "+result[0]+"</br>" } document.getElementById("Flist").innerHTML=str; </script> </body> </html>
1.6 正则表达式陷阱
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.