在进行正则校验时,有时候使用 test 方法会经常失效,表现为一会 true 一会 false。
原因
当正则表达式中存在 /g 时,表示进行全局匹配,但是 test 在进行匹配后,会进行 lastIndex 记录,下次再进行匹配时,会从 lastIndex 起进行往后匹配,导致了匹配失效
demo
// 正则表达式
const reg = /^(402658|410062|468203|95555|621299)\d{10}$/g;
reg.test(4026580201759245) // true
reg.lastIndex // 16
reg.test(4026580201759245) // false
解决方案
- 将 /g 取消掉,如下: ```javascript // 正则表达式 const reg = /^(402658|410062|468203|95555|621299)\d{10}$/;
reg.test(4026580201759245) // true reg.lastIndex // 0 reg.test(4026580201759245) // true
- 重置 lastIndex
```javascript
// 正则表达式
const reg = /^(402658|410062|468203|95555|621299)\d{10}$/g;
reg.test(4026580201759245) // true
reg.lastIndex // 16
reg.lastIndex = 0; // 重置
reg.test(4026580201759245) // true