在进行正则校验时,有时候使用 test 方法会经常失效,表现为一会 true 一会 false。

原因

当正则表达式中存在 /g 时,表示进行全局匹配,但是 test 在进行匹配后,会进行 lastIndex 记录,下次再进行匹配时,会从 lastIndex 起进行往后匹配,导致了匹配失效

demo

  1. // 正则表达式
  2. const reg = /^(402658|410062|468203|95555|621299)\d{10}$/g;
  3. reg.test(4026580201759245) // true
  4. reg.lastIndex // 16
  5. 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

  1. - 重置 lastIndex
  2. ```javascript
  3. // 正则表达式
  4. const reg = /^(402658|410062|468203|95555|621299)\d{10}$/g;
  5. reg.test(4026580201759245) // true
  6. reg.lastIndex // 16
  7. reg.lastIndex = 0; // 重置
  8. reg.test(4026580201759245) // true