正则表达式
什么是正则表达式? 正则表达式(Regular Expression)是一种字符串匹配的模式(规则)
使用场景:
- 例如验证表单:手机号表单要求用户只能输入11位的数字 (匹配)
- 过滤掉页面内容中的一些敏感词和高亮搜索关键字(替换)
- 从字符串中获取我们想要的特定部分(提取 )
正则基本使用
正则基本使用分为两步:
举例:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>正则表达式的基本使用</title><style>.box,.box1,.box2 {width: 500px;height: 90px;border: 1px solid rgba(0,0,0,0.3);}</style>
</head><body><h5>原字符串</h5><div class="box">在这个信息爆炸的时代,保持有效的个人联系至关重要。以下是几个关键人物的联系方式,方便大家在需要时能够迅速取得联系。张经理负责业务拓展,手机号为13800138000;技术支援的小李随时待命解决您的问题,可拨打13700137000。</div><h5>将手机号码变红:</h5><div class="box1"></div><h5>提炼手机号码:</h5><div class="box2"></div><script> let str = `在这个信息爆炸的时代,保持有效的个人联系至关重要。以下是几个关键人物的联系方式,方便大家在需要时能够迅速取得联系。张经理负责业务拓展,手机号为13800138000;技术支援的小李随时待命解决您的问题,可拨打13700137000。`// const reg2 = /(1[0-9]{10})/gconst reg2 = /(13800138000)/gdocument.write(`<br><b>13800138000是否存在:</b>`)document.write(reg2.test(str))let repStr = str.replace(reg2,`<span style="color:red;">$1</span>`)let res = str.match(reg2)document.querySelector('.box1').innerHTML = repStrdocument.querySelector('.box2').innerHTML = res.join('<br>')</script>
</body></html>
- 定义规则
const reg = /表达式/
-
- 其中
/ /
是正则表达式字面量
- 其中
-
- 正则表达式也是
对象
- 正则表达式也是
- 使用正则
-
test()方法
用来查看正则表达式与指定的字符串是否匹配
-
-
- 如果正则表达式与指定的字符串匹配 ,返回
true
,否则false
- 如果正则表达式与指定的字符串匹配 ,返回
-
-
replace()方法
用来替换正则表达式匹配的内容
-
-
- 返回替换以后的完整字符串
- ✨注意:如果要想使用 $1 则需要配合 ()
-
-
match()
用来提取指定内容
-
-
- 返回提取到的内容数组
- ✨注意:如果给正则表达式加了()的时候,需要在正则表达式后面加 g 才能提取正常个数的数据 例如:
/(表达式)/g
-
-
-
- ✨g 是单词 global 的缩写,匹配所有满足正则表达式的结果
- ✨i 是单词 ignore 的缩写,正则匹配时字母不区分大小写
-
元字符
- 普通字符:
- 大多数的字符仅能够描述它们本身,这些字符称作普通字符,例如所有的字母和数字等
- 普通字符只能够匹配字符串中与它们相同的字符。
- 比如: /13800138000/ 只固定匹配 13800138000 这个手机号码
- 比如,规定用户只能输入英文26个英文字母,使用普通字符表达 /[abcdefghijklmnopqrstuvwxyz]/
- 元字符(特殊字符)
- 是一些具有特殊含义的字符,可以极大提高了灵活性和强大的匹配功能。
- 比如,匹配手机号码,换成元字符的写法:/1[0-9]{10}/
- 比如,规定用户只能输入英文26个英文字母,换成元字符写法: /[a-z]/
边界符
正则表达式中的边界符(位置符)用来提示字符所处的位置,主要有两个字符
如果 ^ 和 $ 在一起,表示必须是精确匹配
<body><script>// 元字符之边界符// 1. 匹配开头的位置 ^const reg = /^web/console.log(reg.test('web前端')) // trueconsole.log(reg.test('前端web')) // falseconsole.log(reg.test('前端web学习')) // falseconsole.log(reg.test('we')) // false// 2. 匹配结束的位置 $const reg1 = /web$/console.log(reg1.test('web前端')) // falseconsole.log(reg1.test('前端web')) // trueconsole.log(reg1.test('前端web学习')) // falseconsole.log(reg1.test('we')) // false // 3. 精确匹配 ^ $const reg2 = /^web$/console.log(reg2.test('web前端')) // falseconsole.log(reg2.test('前端web')) // falseconsole.log(reg2.test('前端web学习')) // falseconsole.log(reg2.test('we')) // false console.log(reg2.test('web')) // trueconsole.log(reg2.test('webweb')) // flase </script></body>
量词
量词用来设定某个模式重复次数
注意: 逗号左右两侧千万不要出现空格
<body><script>// 元字符之量词// 1. * 重复次数 >= 0 次const reg1 = /^w*$/console.log(reg1.test('')) // trueconsole.log(reg1.test('w')) // trueconsole.log(reg1.test('ww')) // trueconsole.log('-----------------------')// 2. + 重复次数 >= 1 次const reg2 = /^w+$/console.log(reg2.test('')) // falseconsole.log(reg2.test('w')) // trueconsole.log(reg2.test('ww')) // trueconsole.log('-----------------------')// 3. ? 重复次数 0 || 1 const reg3 = /^w?$/console.log(reg3.test('')) // trueconsole.log(reg3.test('w')) // trueconsole.log(reg3.test('ww')) // falseconsole.log('-----------------------')// 4. {n} 重复 n 次const reg4 = /^w{3}$/console.log(reg4.test('')) // falseconsole.log(reg4.test('w')) // flaseconsole.log(reg4.test('ww')) // falseconsole.log(reg4.test('www')) // trueconsole.log(reg4.test('wwww')) // falseconsole.log('-----------------------')// 5. {n,} 重复次数 >= n const reg5 = /^w{2,}$/console.log(reg5.test('')) // falseconsole.log(reg5.test('w')) // falseconsole.log(reg5.test('ww')) // trueconsole.log(reg5.test('www')) // trueconsole.log('-----------------------')// 6. {n,m} n =< 重复次数 <= mconst reg6 = /^w{2,4}$/console.log(reg6.test('w')) // falseconsole.log(reg6.test('ww')) // trueconsole.log(reg6.test('www')) // trueconsole.log(reg6.test('wwww')) // trueconsole.log(reg6.test('wwwww')) // false// 7. 注意事项: 逗号两侧千万不要加空格否则会匹配失败</script>
范围
表示字符的范围,定义的规则限定在某个范围,比如只能是英文字母,或者数字等等,用表示范围
<body><script>// 元字符之范围 [] // 1. [abc] 匹配包含的单个字符, 多选1const reg1 = /^[abc]$/console.log(reg1.test('a')) // trueconsole.log(reg1.test('b')) // trueconsole.log(reg1.test('c')) // trueconsole.log(reg1.test('d')) // falseconsole.log(reg1.test('ab')) // false// 2. [a-z] 连字符 单个const reg2 = /^[a-z]$/console.log(reg2.test('a')) // trueconsole.log(reg2.test('p')) // trueconsole.log(reg2.test('0')) // falseconsole.log(reg2.test('A')) // false// 想要包含小写字母,大写字母 ,数字const reg3 = /^[a-zA-Z0-9]$/console.log(reg3.test('B')) // trueconsole.log(reg3.test('b')) // trueconsole.log(reg3.test(9)) // trueconsole.log(reg3.test(',')) // flase// 用户名可以输入英文字母,数字,可以加下划线,要求 6~16位const reg4 = /^[a-zA-Z0-9_]{6,16}$/console.log(reg4.test('abcd1')) // false console.log(reg4.test('abcd12')) // trueconsole.log(reg4.test('ABcd12')) // trueconsole.log(reg4.test('ABcd12_')) // true// 3. [^a-z] 取反符const reg5 = /^[^a-z]$/console.log(reg5.test('a')) // false console.log(reg5.test('A')) // trueconsole.log(reg5.test(8)) // true</script></body>
案例1-练习test,match,replace
使用正则表达式实现如下需求:
- 使用正则表达式将【原字符串】中的所有电话号码替换成【红色】 - replace
- 使用正则表达式,提取出所有的电话号码 - match
- 判断是否存在136开头的电话号码 - test
/(1[0-9]{10})/g
/(136[0-9]{8})/g
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>正则表达式的基本使用</title><style>.box,.box1,.box2 {width: 500px;height: 90px;border: 1px solid rgba(0,0,0,0.3);}</style>
</head><body><h5>原字符串</h5><div class="box">在这个信息爆炸的时代,保持有效的个人联系至关重要。以下是几个关键人物的联系方式,方便大家在需要时能够迅速取得联系。张经理负责业务拓展,手机号为13800138000;技术支援的小李随时待命解决您的问题,可拨打13700137000。</div><h5>将手机号码变红:</h5><div class="box1"></div><h5>提炼手机号码:</h5><div class="box2"></div><script> let str = `在这个信息爆炸的时代,保持有效的个人联系至关重要。以下是几个关键人物的联系方式,方便大家在需要时能够迅速取得联系。张经理负责业务拓展,手机号为13800138000;技术支援的小李随时待命解决您的问题,可拨打13700137000。`const reg2 = /(1[0-9]{10})/g// const reg2 = /(13800138000)/// const reg2 = /(1\d{10})/gdocument.write(`<br><b>否存在136开头的电话号码:</b>`)const reg3 = /(136[0-9]{8})/gdocument.write(reg3.test(str))let repStr = str.replace(reg2,`<span style="color:red;">$1</span>`)let res = str.match(reg2)console.log(res);document.querySelector('.box1').innerHTML = repStrdocument.querySelector('.box2').innerHTML = res.join('<br>')</script>
</body></html>
案例2:用户名验证
📎images.rar
需求:用户名要求用户英文字母,数字,下划线或者短横线组成,并且用户名长度为 6~16 位
分析:
①:首先准备好正则表达式(无需自己编写,AI:生成一个6到16位数字字母-_组合的正则表达式) /^[a-zA-Z0-9-_]{6,16}$/
②:当表单失去焦点就开始验证.(blur事件)
③:如果符合正则规范, 则让后面的span标签添加 right 类
④:如果不符合正则规范, 则让后面的span标签添加 wrong 类,同时显示提示框(.tip)
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>验证用户名案例</title><style>dt,dd {margin: 0;position: relative;}dl {display: flex;width: 600px;height: 30px;line-height: 30px;}dl dt {margin-right: 5px;}dl input {width: 269px;height: 28px;padding-left: 5px;border: 1px solid #ccc;outline: none;background: transparent;line-height: 30px;border-radius: 5px;}.tip {display: none;position: relative;width: 220px;height: 30px;margin-left: 15px;border: 1px solid #f59fb1;color: #d93c3c;text-align: center;font-size: 14px;background-color: #fff2f5;border-radius: 5px;}.tip::before {content: '';position: absolute;top: 50%;left: -6px;width: 10px;height: 10px;background-color: #fff2f5;border-left: 1px solid #f59fb1;border-bottom: 1px solid #f59fb1;transform: translateY(-50%) rotate(45deg);}span {position: absolute;top: 9px;right: 10px;width: 15px;height: 15px;}.right {background: url(./images/right.png) no-repeat;}.wrong {background: url(./images/error1.png) no-repeat;}</style>
</head><body><dl><dt>用户名:</dt><dd><input type="text" class="uname"><span id="icon"></span></dd><dd class="tip">输入6~16位数字字母-_组成</dd></dl><script>// 1. 准备正则表达式(AI帮生成)// 输入6~16位数字字母-_组成const reg = /^[a-zA-Z0-9_-]{6,16}$/// 2. 给文本框注册blur事件const inputBox = document.querySelector('.uname')const iconBox = document.querySelector('#icon')inputBox.addEventListener('blur', function () {// 1. 获取用户的输入let userInput = inputBox.value// 2. 用正则来匹配用户的输入是否符合要求let isOK = reg.test(userInput)// 3. 利用isOK的结果进行提示显示if (isOK) {// 这里是表示验证通过// inputBox.nextElementSiblingiconBox.className = 'right'document.querySelector('.tip').style.display = 'none'} else {// 这里是表示验证不通过iconBox.className = 'wrong'document.querySelector('.tip').style.display = 'block'}})</script></body></html>
字符类
某些常见模式的简写方式,区分字母和数字
/^\d{4}-\d{1,2}-\d{1,2}$/
案例3:利用正则隐藏手机号中间四位
实现如下需求:
- 手机号前三位显示,中间四位隐藏为****, 后面四位显示
分析:
- 把手机号利用正则利用小括号划分为三部分 /^(\d{3})\d{4}(\d{4})$/
- 使用正则配合replace方法完成*的替换, $1 对应第一个小括号内容,$2 对应第2个括号内容,依次类推
- 将replace方法的返回内容放到页面元素里
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>隐藏手机号中间四位案例.</title><style>.wrapper {width: 840px;height: 420px;background: url(./images/bg01.jpg) no-repeat center / cover;padding: 100px 250px;box-sizing: border-box;}.wrapper strong {font-size: 50px;}.wrapper span {color: #b10e0d;}</style>
</head><body><div class="wrapper"><strong>年会抽奖</strong><h1>获奖手机号:<span class="phone">???</span></h1></div><script></script>
</body></html>
<script>// 隐藏手机号中间四位案例const tel = '13611112222'// 1. 利用正则划分手机号const reg = /^(\d{3})\d{4}(\d{4})$/// 2. 利用replace 替换 // $1 可以得到正则中第一个小括号里面的内容// $2 可以得到正则中第二个小括号里面的内容const str = tel.replace(reg, '$1****$2')document.querySelector('.phone').innerHTML = str</script>
正则插件
综合案例
实现小兔鲜页面注册表单元素校验
分析:
- 使用正则验证【用户名】、【手机】、【验证码】、【密码】
-
- 用户名:
const regName = /^[a-zA-Z0-9-_]{6,10}$/
- 手机:
const regPhone = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
- 验证码:
const regCode = /^\d{6}$/
- 密码:
const regPwd = /^[a-zA-Z0-9-_]{6,20}$/
- 用户名:
- 确认密码验证-> 使用【密码框】输入的值 是否等于【再次输入密码框】的值
- 是否勾选了已阅读验证
.icon-queren 是默认类没选中
.icon-queren2 则是选中样式
使用 document.querySelector('.icon-queren').classList.contains('icon-queren2') 可以判断是否存在某个class
静态模版和实现均在下面rar包中
综合案例.rar
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>小兔鲜儿 - 新鲜 惠民 快捷!</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="renderer" content="webkit"><link rel="shortcut icon" href="./favicon.ico"><link rel="stylesheet" href="./css/common.css"><link rel="stylesheet" href="./css/register.css"><link rel="stylesheet" href="https://at.alicdn.com/t/font_2143783_iq6z4ey5vu.css"><style>.msg {display: none;}</style>
</head><body><!-- 项部导航 --><div class="xtx_topnav"><div class="wrapper"><!-- 顶部导航 --><ul class="xtx_navs"><li><a href="./login.html">请先登录</a></li><li><a href="./register.html">免费注册</a></li><li><a href="./center-order.html">我的订单</a></li><li><a href="./center.html">会员中心</a></li><li><a href="javascript:;">帮助中心</a></li><li><a href="javascript:;">在线客服</a></li><li><a href="javascript:;"><i class="mobile sprites"></i>手机版</a></li></ul></div></div><!-- 头部 --><div class="xtx_header"><div class="wrapper"><!-- 网站Logo --><h1 class="xtx_logo"><a href="/">小兔鲜儿</a></h1><!-- 主导航 --><div class="xtx_navs"><ul class="clearfix"><li><a href="./index.html">首页</a></li><li><a href="./category01.html">生鲜</a></li><li><a href="./category01.html">美食</a></li><li><a href="./category01.html">餐厨</a></li><li><a href="./category01.html">电器</a></li><li><a href="./category01.html">居家</a></li><li><a href="./category01.html">洗护</a></li><li><a href="./category01.html">孕婴</a></li><li><a href="./category01.html">服装</a></li></ul></div><!-- 站内搜索 --><div class="xtx_search clearfix"><!-- 购物车 --><a href="./cart-none.html" class="xtx_search_cart sprites"><i>2</i></a><!-- 搜索框 --><div class="xtx_search_wrapper"><input type="text" placeholder="搜一搜" onclick="location.href='./search.html'"></div></div></div></div><div class="xtx-wrapper"><div class="container"><!-- 卡片 --><div class="xtx-card"><h3>新用户注册</h3><form class="xtx-form"><div data-prop="username" class="xtx-form-item"><span class="iconfont icon-user"></span><input name="username" type="text" placeholder="设置用户名称"><span class="msg">请输入6~10位</span></div><div data-prop="phone" class="xtx-form-item"><span class="iconfont icon-phone"></span><input name="phone" type="text" placeholder="输入手机号码 "><span class="msg">请输入11位的数字</span></div><div data-prop="code" class="xtx-form-item"><span class="iconfont icon-code"></span><input name="code" type="text" placeholder="短信验证码"><span class="msg">请输入6位的数字</span><a class="code" href="javascript:;">发送验证码</a></div><div data-prop="password" class="xtx-form-item"><span class="iconfont icon-lock"></span><input name="password" type="password" placeholder="设置6至20位字母、数字和符号组合"><span class="msg">请输入6~20位的字母数字下划线和短横线组成</span></div><div data-prop="confirm" class="xtx-form-item"><span class="iconfont icon-lock"></span><input name="confirm" type="password" placeholder="请再次输入上面密码"><span class="msg">两次密码不一致</span></div><div class="xtx-form-item pl50"><i class="iconfont icon-queren"></i>已阅读并同意<i>《用户服务协议》</i><span class="msg">请勾选协议</span></div><div class="xtx-form-item"><button class="submit">下一步</button><!-- <a class="submit" href="javascript:;">下一步</a> --></div></form></div></div></div><!-- 公共底部 --><div class="xtx_footer clearfix"><div class="wrapper"><!-- 联系我们 --><div class="contact clearfix"><dl><dt>客户服务</dt><dd class="chat">在线客服</dd><dd class="feedback">问题反馈</dd></dl><dl><dt>关注我们</dt><dd class="weixin">公众号</dd><dd class="weibo">微博</dd></dl><dl><dt>下载APP</dt><dd class="qrcode"><img src="./uploads/qrcode.jpg"></dd><dd class="download"><span>扫描二维码</span><span>立马下载APP</span><a href="javascript:;">下载页面</a></dd></dl><dl><dt>服务热线</dt><dd class="hotline">400-0000-000<small>周一至周日 8:00-18:00</small></dd></dl></div></div><!-- 其它 --><div class="extra"><div class="wrapper"><!-- 口号 --><div class="slogan"><a href="javascript:;" class="price">价格亲民</a><a href="javascript:;" class="express">物流快捷</a><a href="javascript:;" class="quality">品质新鲜</a></div><!-- 版权信息 --><div class="copyright"><p><a href="javascript:;">关于我们</a><a href="javascript:;">帮助中心</a><a href="javascript:;">售后服务</a><a href="javascript:;">配送与验收</a><a href="javascript:;">商务合作</a><a href="javascript:;">搜索推荐</a><a href="javascript:;">友情链接</a></p><p>CopyRight © 小兔鲜儿</p></div></div></div></div><script>// 表单元素dom对象const usernameBox = document.querySelector('[name=username]')const phoneBox = document.querySelector('[name=phone]')const codeBox = document.querySelector('[name=code]')const passwordBox = document.querySelector('[name=password]')const confirmBox = document.querySelector('[name=confirm]')// 正则表达式const regName = /^[a-zA-Z0-9-_]{6,10}$/const regPhone = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/const regCode = /^\d{6}$/const regPwd = /^[a-zA-Z0-9-_]{6,20}$/// 验证function validate(reg, box) {let isOk = reg.test(box.value)if (isOk) {box.nextElementSibling.style.display = 'none'} else {box.nextElementSibling.style.display = 'block'}return isOk}usernameBox.addEventListener('blur', function () {validate(regName, usernameBox)})phoneBox.addEventListener('blur', function () {validate(regPhone, phoneBox)})codeBox.addEventListener('blur', function () {validate(regCode, codeBox)})passwordBox.addEventListener('blur', function () {validate(regPwd, passwordBox)})function validateConfimPwd() {let isOK = passwordBox.value === confirmBox.valueif (isOK) {confirmBox.nextElementSibling.style.display = 'none'} else {confirmBox.nextElementSibling.style.display = 'block'}return isOK}confirmBox.addEventListener('blur', function () {validateConfimPwd()})const ckBox = document.querySelector('.icon-queren')ckBox.addEventListener('click', function () {this.classList.toggle('icon-queren2')isChecked()})function isChecked(){ let isOK = ckBox.classList.contains('icon-queren2')if (isOK) {ckBox.nextElementSibling.nextElementSibling.style.display = 'none'} else {ckBox.nextElementSibling.nextElementSibling.style.display = 'block'}return isOK}// 提交const btBox = document.querySelector('.submit')btBox.addEventListener('click', function (e) {e.preventDefault()let nameOK = validate(regName, usernameBox)let phoneOK = validate(regPhone, phoneBox)let codeOK = validate(regCode, codeBox)let pwdOK = validate(regPwd, passwordBox)let confimOK = validateConfimPwd()let isCheckedOK = isChecked()if (nameOK && phoneOK && codeOK && pwdOK &&confimOK &&isCheckedOK) {alert('😊恭喜,验证通过')}else{alert('😒验证失败,请修改表单数据') }})</script>
</body></html>