6.3 正则表达式
正则表达式(Regular Expression):主要用在字符串格式匹配方面
6.3.1 常用正则表达式符号
6.3.2 常用限定符符号
6.3.3 常用的反义代码
正则表达式当中的小括号()优先级较高。
[1-9] 表示 1 到 9 的任意 1 个数字(次数是 1 次。)
[A-Za-z0-9] 表示 A-Z、a-z、0-9 中的任意 1 个字符
[A-Za-z0-9-] 表示 A-Z、a-z、0-9、- ,以上所有字符中的任意 1 个字符
简单的正则表达式要会写
QQ 号的正则表达式:^[1-9][0-9]{4,}$
email 正则:^\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$
6.3.4 创建表达式对象以及调用方式
创建方式:
关于 flag 后面的参数:
g:全局匹配
i:忽略大小写
m:多行搜索(ES 规范制定之后才支持 m)
当前面是正则表达式的时候,m 不能用
只有前面是普通字符串的时候,m 才可以使用
调用方式:
正则表达式对象的 test()方法
true / false = 正则表达式对象.test(用户填写的字符串);
复制代码
true : 字符串格式匹配成功
false: 字符串格式匹配失败
6.3.5 验证邮箱格式
1.代码示例验证邮箱是否正确光标如果回去需要将验证正确与否剔除
<body>
<script type="text/javascript">window.onload = function(){ // 给按钮绑定click document.getElementById("btn").onclick = function(){ var email = document.getElementById("email").value; var emailRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; var ok = emailRegExp.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: 12px;"></span> <br><input type="button" value="验证邮箱" id="btn" />
</body>
复制代码
输入邮箱验证成功
如果光标回去文本框 需要清除右边那个提示,则需要绑定其他
// 给文本框绑定focusdocument.getElementById("email").onfocus = function(){ document.getElementById("emailError").innerText = "";}
复制代码
6.3.6 扩展字符串 trim 函数
去除字符串的前后空白 trim
<body> <script type="text/javascript"> window.onload = function(){ document.getElementById("btn").onclick = function(){ // 获取用户名 var username = document.getElementById("username").value; // 去除前后空白 username = username.trim(); // 测试 alert("--->" + username + "<----"); } } </script> <input type="text" id="username" /> <input type="button" value="获取用户名" id="btn" /></body>
复制代码
String.prototype.trim = function(){ // 去除当前字符串的前后空白 // 在当前的方法中的this代表的就是当前字符串. //return this.replace(/^\s+/, "").replace(/\s+$/, ""); return this.replace(/^\s+|\s+$/g, "");}
复制代码
return this.replace(/^\s+/, "").replace(/\s+$/, "");
复制代码
这行代码第一个 replace 是前空格字符串,后一个 replace 是后空格字符串,/ 字符串/ ,^是开头,$是结尾,\s 是空白字符串,+1 个到多个字符串。
prototype 可以扩展属性
评论