括弧子字串的比對結果的運用
在正規表達式的模式中包含括弧,對應的子比對結果就會被記憶。舉例來說,/a(b)c/
比對字元 'abc' 並把 'b' 記憶起來。若要取回括弧子字串的比對結果,就使用 Array 元素 [1], ..., [n]。
括弧子字串的可能數目並沒有限制。返回的陣列保留了所有找到的子字串。以下範例解說如何使用括弧子字串的比對結果。
範例 1
以下 Script 使用 replace
方法來置換字串裡的文字。對於那些替換用的文字,Script 使用了 $1
和 $2
來表示第一個和第二個括弧子字串的比對結果。
<script type="text/javascript"> re = /(\w+)\s(\w+)/; str = "John Smith"; newstr = str.replace(re, "$2, $1"); document.write(newstr); </script>
本例輸出 "Smith, John"。
範例 2
附註: 在 getInfo
函數中,exec
方法是以 () 省略記法所呼叫的,這個記法在 Firefox 可以運作,其他瀏覽器則不一定。
<html> <script type="text/javascript"> function getInfo(field){ var a = /(\w+)\s(\d+)/(field.value); window.alert(a[1] + ", your age is " + a[2]); } </script> Enter your first name and your age, and then press Enter. <form> <input type="text" name="NameAge" onchange="getInfo(this);"> </form> </html>