javascript正則表達式對象方法 compile() exec() test()的比較

compile() 方法用於在腳本執行過程中編譯正則表達式,也可用於改變和重新編譯正則表達式。

exec() 方法用於檢索字符串中的正則表達式的匹配。找到則返回一個數組,未找到則返回null。

test() 方法用於檢測一個字符串是否匹配某個模式。返回true 或 false.

語法:

compile():
RegExpObject.compile(regexp,modifier)
regexp 正則表達式。
modifier 規定匹配的類型。"g" 用於全局匹配,"i" 用於區分大小寫,"gi" 用於全局區分大小寫的匹配。


RegExpObject.exec(string)
string 要檢索的字符串。


RegExpObject.test(string)
string 要檢測的字符串。




<script type="text/javascript">
    var str="Every man in the world! Every woman on earth!";

    patt=/man/g;
    str2=str.replace(patt,"person");
    document.write(str2+"<br />");patt=/(wo)?man/g;patt.compile(patt);str2=str.replace(patt,"person");
    document.write(str2);
</script>
輸出結果:Every person in the world! Every woperson on earth!
          Every person in the world! Every person on earth!


<script type="text/javascript">
    var str = "good jjdky"; 
    var patt = new RegExp("jjdky","g");
    var result;

    while ((result = patt.exec(str)) != null)  {
    document.write(result);
    document.write("<br />");
    document.write(patt.lastIndex);
 }
</script>
輸出結果:jjdky
          10


<script type="text/javascript">
    var str = "good jjdky";
    var patt1 = new RegExp("jjdky");
    var result = patt1.test(str);
    document.write("Result: " + result);
</script>

輸出結果:Result: true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章