
JavaScript RegExp 對象
compile() 方法用于在腳本執行過程中編譯正規表達式。
compile() 方法也可用于改變和重新編譯正規表達式。
RegExpObject.compile(regexp,modifier)
參數
描述
regexp
正規表達式。
modifier
規定比對的類型。"g" 用于全局比對,"i" 用于區分大小寫,"gi" 用于全局區分大小寫的比對。
除了 Opera 浏覽器外,其他浏覽器都支援 compile() 方法。
在字元串中全局搜尋 "man",并用 "person" 替換。然後通過 compile() 方法,改變正規表達式,用 "person" 替換 "man" 或 "woman",:
<script>
var str="Every man in the world! Every woman on earth!";
var
patt=/man/g;
str2=str.replace(patt,"person");
document.write(str2+"<br>");
patt=/(wo)?man/g;
patt.compile(patt);
document.write(str2);
</script>
以上執行個體輸出結果:
Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!
