Regular problem: judging negative integers

/ / negative integer

re = /^-[0-9]+$/g
console.log("")
console.log("-1 test:   true  ", re.test(-1)) // true
console.log("-2 test:   true  ", re.test(-2)) // false

the second line output is: true
the third line output is: false

Why?

Mar.23,2021

because / g


look at this


remove g from the rule.

when using g , there is a lastIndex inside the regular time to record the last matching position. When the call is repeated, it will continue to match with the last lastIndex, which will lead to an error in judgment.

Menu