有兩種定義方式:html
其中[0-9a-zA-Z]爲字符串匹配規則,i爲修飾符。正則表達式
例子代碼:工具
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>test2</title> </head> <body> <p id="p" style="color:red;"></p> <input id="phone" type="text" name="phone" value='' placeholder="請輸入手機號!"> <input id="btn" type="submit" value="點擊"></input> <script> window.onload = function() { var btn = document.getElementById('btn'); var p = document.getElementById('p'); var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/; btn.onclick = function() { var phone = document.getElementById('phone').value; if (reg.test(phone)) { p.innerHTML = '該手機號正確!'; } else { p.innerHTML = '該手機號錯誤!'; } } } </script> </body> </html>