The problem

I recently encountered a strange problem where the same re match returns a different value:

let reg = /^[\sa-zA-Z0-9\u4e00-\u9fa5~!@# $% ^ & * () _ + = {} ` \ | : "< >? [\]; ',. / ~! @ # $%... & * () - + = {}, \ | : "" ""? 【 】,; ', '. /] * [\ sa - zA - Z0-9 \ u4e00 - \ u9fa5 ~! @ # $% ^ & * () _ + = {} ` \ | "" < >? [\]; '. / ~!... @ # $% & * () - + = {}, \ | :" "" "? 【 】,, ' ',. /] $/ gim,

reg.test('1') / /true

reg.test('1') / /false

reg.test('1') / /true

reg.test('1') / /false
Copy the code

Four times the same input but four different outputs:

The reason:

Set the global match because of the global property of the re REg. RegExp has a lastIndex attribute to hold the index starting position. The two starts have different starting values, which results in different results.

Problem solving:

One: Delete the global attribute. By default, the global attribute will not be matched.

Two: Set the value of lastIndex to 0 before each match and start the match from scratch

reg.test('1')
true
reg.lastIndex = 0;
0
reg.test('1')
true
Copy the code

I hope that gives you some idea.