test是RegExp的方法,参数是字符串,返回值是boolean类型。
match是String的方法,参数是正则表达式,返回值是数组。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>demo08.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
//方式1:
function checkEmail(){
//获取输入框的值
var email = document.getElementById("email").value;
//正则
// var reg = /^\w+@\w+(\.\w+){1,2}/; //正确的
// var reg = new RegExp("^\w+@\w+(\.\w+){1,2}"); //错
var reg = new RegExp("^\\w+@\\w+(\\.\\w+){1,2}"); //正确的,注意加\\
if(reg.test(email)){
alert("校验通过");
}else{
alert("邮箱格式不正确");
}
}
//方式2:
function checkEmail2(){
//获取输入框的值
var email = document.getElementById("email").value;
//正则
var reg = /^\w+@\w+(\.\w+){1,2}/;
if(email.match(reg)!=null){
alert("校验通过");
}else{
alert("邮箱格式不正确");
}
}
</script>
</head>
<body>
请输入邮箱:<input type="text" id="email" />
<input type="button" value="校验1" onclick="checkEmail()"/>
<input type="button" value="校验2" onclick="checkEmail2()"/>
</body>
</html>