1.6 正則表達式陷阱

<!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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章