js正則表示式()和$1...$9的理解和使用
阿新 • • 發佈:2019-01-31
1.小括號的意思
這是百度百科中的:
(pattern) |
匹配pattern並獲取這一匹配。所獲取的匹配可以從產生的Matches集合得到,在VBScript中使 用SubMatches集合,在JScript中則使用$0…$9屬性。要匹配圓括號字元,請使用“”或“”。 |
2.我的理解
()就是起到一個分組作用,將匹配到的放到mathches集合中,$相當於集合名字,1-9就相當於索引,$1...$9相當於對應索引的值。
3.使用()和$1...$9來限制輸入位數
例如只能輸入四位正整數的input框:
<html> <title>正則表示式</title> <head> <meta charset="utf-8"> </head> <script type="text/javascript"> //只能輸入1-9999正整數 function clearInput(obj){ obj.value = obj.value.replace(/[^\d]/g,""); obj.value = obj.value.replace(/^0.*$/g,""); obj.value = obj.value.replace(/^([1-9])(\d{3}).*$/,'$1$2'); //只能輸入兩個小數 } function alertMessage(){ var value=document.getElementById('digit').value; var regx=/\d{3}/; if (regx.test(value)) { alert("是3位"); }else{ alert("不是3位"); }; } </script> <body> 四位正整數:<input id="digit" type="text" onkeyup="clearInput(this)" onafterpaste="clearInput(this)"> <input type="button" onclick="alertMessage()" value="有幾位數字"> </body> <html></span>
^([1-9]) 是$1
(\d{3})是$2
總結:()和$1...$9結合使用是個很好的工具