21、正则操作DOM元素
<body>
<input type="text" name="username">
<p>pppp</p>
<h1>h11111</h1>
<h2>222222</h2>
<h3>3333333</h3>
</body>
<script>
let body = document.body;
let reg = /<(h[1-6])>[\s\S]*<\/\1>/gi;
console.log(body.innerHTML);
body.innerHTML = body.innerHTML.replace(reg,'');
console.log(body.innerHTML);
</script>
22、认识原子组
23、邮箱验证中原子组的使用
<body>
<input type="text" name="mail" value="223-2459-332@qq.com">
<input type="text" name="otherMail" value="22-32-459332@qq.com.cn">
</body>
<script>
let mail = document.querySelector(`[name='mail']`).value;
let reg = /^[\w\-]+@[\w\-]+\.(com|org|cc|cn|net)$/i;
console.log(mail.match(reg));
let otherMail = document.querySelector(`[name='otherMail']`).value;
let otherReg = /^[\w\-]+@([\w\-]+\.)+(com|org|cc|cn|net)$/i;
console.log(otherMail.match(otherReg));
</script>
24、原子组引用完成替换操作
let hd = `
<h1>wujunjie.com</h1>
<span>hahaha</span>
<h2>hihihihi</h2>
`;
let reg = /<(h[1-6])>([\s\S]+)<\/\1>/gi;
console.log(hd);
console.log(hd.match(reg));
console.log(hd.replace(reg, `<p>$2</p>`));
let res = hd.replace(reg, (p0,p1,p2) => {
console.log(p0,p1,p2);
return `<p>${p2}</p>`;
});
console.log(res);
25、嵌套分组与不记录组
let str = `https://www.junjie.fun
http://wujunjie.com
https://yuanxiaorong.com
`;
let reg = /https?:\/\/((\w+\.)?\w+\.(fun|com|cn|org))/gi
console.log(str.match(reg));
let newReg = /https?:\/\/(\w+\.\w+\.(?:fun|com|cn|org))/
console.log(str.match(newReg));
while(res = reg.exec(str)) {
console.log(res[1]);
}
26、多种重复匹配基本使用
27、批量使用正则完成密码验证
<body>
<input type="text" name="password">
</body>
<script>
const userPW = document.querySelector(`[name=password]`);
userPW.addEventListener('keyup',(e) => {
const value = e.target.value;
const regs = [/^[a-z0-9]{5,10}$/i, /[A-Z]/, /[0-9]/];
let state = regs.every(e => e.test(value));
console.log(state ? '正确' : '错误');
})
</script>
28、禁止贪婪
let hd = 'hdddd';
console.log(hd.match(/hd*/));
console.log(hd.match(/hd+/));
console.log(hd.match(/hd*?/));
console.log(hd.match(/hd+?/));
console.log(hd.match(/hd{2,3}?/));
console.log(hd.match(/hd??/))
29、标签替换的禁止贪婪使用
<body>
<p>
<span>wujunjie.fun</span>
<span>junjie.com</span>
<span>wu.cn</span>
</p>
</body>
<script>
const main = document.querySelector('p');
const reg = /<span>[\s\S]+<\/span>/gi;
const newReg = /<span>[\s\S]+?<\/span>/gi;
main.innerHTML.replace(reg, v => {
console.log(v);
})
main.innerHTML.replace(newReg, v => {
console.log(v);
})
</script>
30、使用matchAll完成全局匹配
<body>
<p>
<span>wujunjie.fun</span>
<span>junjie.com</span>
<span>wu.cn</span>
</p>
</body>
<script>
let reg = /<span>([\s\S]+?)<\/span>/gi;
const p = document.querySelector('p');
const hd1 = p.innerHTML.match(reg);
console.log(hd1);
const hd = p.innerHTML.matchAll(reg);
console.log(hd);
for(const iterator of hd) {
console.log(iterator);
console.log(iterator[1]);
}
</script>