Chapter 14 Regular Expression Example html body bgcolorcornsilk

Chapter 14 Regular Expression



Example <html> <body bgcolor=cornsilk> 請輸入你的電話號碼, 要用國際格式, 例如 +852 12345678 : <form name=fm> <input type=text name=tx on. Change="check. It( )"> </form> <script> function check. It( ) { re=/^s*x 2 bddds+d{4}s*$/ x = document. fm. tx. value. search(re) if (x==-1) alert("Invalid telephone number! ") else alert(" O K ") } </script> </body> </html>

Regular expression 的設定 n n 設定一個 regular expression 有以下兩個語法, /pattern/flag 或 new Reg. Exp("pattern", "flag") 我們一般會用 re (自訂的變數名稱) 來代表一 個 regular expression, 所以會有以下的 statements: re=/pattern/flag 或 re=new Reg. Exp("pattern", "flag") Note: 這處的 pattern 是指文字方程式, flag 可以是 g、i 或 gi , 隨後會有解釋


Example <html> <body bgcolor=mintcream> <form name=fm> <input type=text name=tx size=50 on. Change="check. It( )" > </form> <script> function check. It( ) { re=/apple|orange/gi x = document. fm. tx. value. match(re) alert(x) } </script> </body> </html>












Example <html> <body bgcolor=azure> <form name=fm> Please fill in three colors you like most. <input type=text name=tx size=20> <input type=button value=" OK " on. Click=check. It( )> </form> <script> function check. It( ) { re =/(w+)s+(w+)/ document. fm. tx. value. match(re) alert("The three colors you like most are: n 1. " + Reg. Exp. $1 + "n 2. " + Reg. Exp. $2 + "n 3. " + Reg. Exp. $3 ) } </script> </body> </html>
- Slides: 19