- Overview
- 功能强大;更多使用请访问 i hate regex
- match
- 查找匹配的串并输出结果
-
> let re=/\d+/g;
undefined
> re
/\d+/g
> console.log('123 234 456'.match(re))
[ '123', '234', '456' ]
- replace
- 替换匹配的串
- [] 隐藏手机中间4位
- 隐藏前:52188881314
- 隐藏后:52188881314
-
let cell0 = document.querySelector('.cell0');
let reg0 = /^(\d{3})\d{4}(\d{4})$/
cell0.innerHTML = cell0.innerHTML.replace(reg0, '$1****$2')
- [] DD打车只显示手机后4位
- 隐藏前:52188881314
- 隐藏后:52188881314
-
let cell1 = document.querySelector('.cell1');
let reg1 = /^\d{7}(\d{4})$/
cell1.innerHTML = cell1.innerHTML.replace(reg1, '*******$1')
- [] 编辑结构 - 将每个字符都套上1个<span>
- . $&表示匹配到的字符
-
let h1 = document.querySelector('h1')
h1.innerHTML = h1.innerHTML.replace(/\S/g, '<span>$&</span>')