正则表达式作用是匹配字符串。
怎么创建正则表达式对象,怎么调用正则表达式对象的方法?
第一种创建方法:
var reExp = /正则表达式/flags;
第二种创建方式:使用内置类RegExp
var regExp = new RegExp("正则表达式","flags");
关于flags:
g:全局匹配
i:忽略大小写
m:多行搜索(ES规范制定之后才有的m),当前面是正则表达式时,m不能用。只有前面是普通普通字符串时,m才能使用。
正则表达式对象的test()方法:
正则表达式.test(用户太难写的字符串); 返回true/false。
当返回为true时:表示字符串格式配成功。
当返回为false时:表示字符串格式配失败。
邮箱验证:
<html>
<body>
<script>
window.onload = function(){
document.getElementById("btn").onclick = function(){
var email = document.getElementById("email").value;
var emailReExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var ok = emailReExp .test(email);
if(ok){
document.getElementById("emailError").innerText="邮箱地址合法"
}else{
document.getElementById("emailError").innerText="邮箱地址不合法"
}
}
//给文本狂绑定focus
document.getElementById("email").onfocus = function(){
document.getElementById("emailError").innerText= "";
}
}
</script>
<input type ="text" id="email" />
<span id="emailError" style="color: red;font-size: 12ps;"></span>
<br>
<input type="button" value="验证邮箱" id="btn" />
</body>
</html>