1、普通方式
let hd = 'debounce';
let a = 'de'
console.log(/a/.test(hd))
console.log(eval(`/${a}/`).test(hd));
2、对象方式创建
let hd = 'houdunren.com';
let a = '@';
let reg = new RegExp(a,'g');
console.log(reg.test(hd));
console.log('abc'.replace(/\w/g,search => {
return '你好';
}))
let con = prompt('请输入要检测的内容,支持正则');
let reg2 = new RegExp(con, 'g');
let div = document.querySelector('div');
div.innerHTML = div.innerHTML.replace(reg2, search => {
return `<span style="color:red">${search}</span>`
})
3、增加选择符
let hd = 'hundunren';
console.log(/aaau|@/.test(hd));
let tel = '010-9999999';
console.log(/(010|020)\-\d{7,8}/.test(tel));
4、原子表与原子组
let reg = /[12345]/;
let reg2 = /(12|34)/;
let hd = '1111234';
console.log(hd.match(reg))
console.log(hd.match(reg2))
5、转义
let price1 = '23@34';
let price2 = 23.34;
console.log(/\d+.\d+/.test(price1));
console.log(/\d+.\d+/.test(price2));
console.log(/\d+\.\d+/.test(price1));
console.log(/\d+\.\d+/.test(price2));
let reg = new RegExp('\\d+\\.\\d+');
console.log(reg.test(price1))
console.log(reg.test(price2))
let url = 'https://www.junjie.com';
console.log(/https?:\/\/\w+\.\w+\.\w+/.test(url));
6、边界约束
<input type="text" name='user'>
<span/>
let hd = '3sdfsdfd4';
console.log(/^\d$/.test(hd));
document.querySelector('[name=user]').addEventListener('keyup',function() {
let flag = this.value.match(/^[a-z]{3,6}$/);
document.querySelector('span').innerHTML = flag ? 'true' : 'false'
})
7、数值与空白元字符
let hd = 'wujunjie jiayou 2010';
console.log(hd.match(/\d/g))
console.log(hd.match(/\d+/))
let hh = `张三:010-99999999,李四:
020-88888888`;
console.log(hh.match(/\d{3}-\d{7,8}/g))
console.log(hd.match(/\D+/))
console.log(hd.match(/\D/g))
console.log(hh.match(/[-\d/\n:,]/g))
console.log(hh.match(/[^-\d:,]/g))
console.log(/\s/.test('\nhd'));
console.log(/\S/.test('\n'))
console.log(hh.match(/[^-\d:,\s]+/g))
8、W涉及的元字符
let email = '2232459332@qq.com';
console.log(email.match(/^\d+@\w+\.\w+$/));
let hd = 'a1234566*6';
console.log(/^[a-z]\w{4,9}$/.test(hd));
9、点元字符的使用
let hd = '\nwujunjie\n'
console.log(hd.match(/.+/));
console.log(hd.match(/^.+/));
let tel = '0001 - 0101001'
console.log(tel.match(/\d+ - \d+/));
console.log(tel.match(/\d+\s-\s\d+/));
10、匹配所有字符
let hd = `<span>
hundunren @@@@
hdcms
</span>`
console.log(hd.match(/[\d\D]+/))