Was working on some regex in JS and noticed something strange when using a negative set. It seems that for some reason the ‘^’ is not matched by the following negative set:
[^a-zA-z0-9]
When I attempt to do a replace on the following string, it results in just the ‘^’ character left:
"'"&@#$%^&".replaceAll(/[^a-zA-z0-9]/g,"") // Result: '^'
Why is this happening? Shouldn’t the negative set match the ‘^’ since it is not found in any of the ranges supplied?
I’ve included the example as a snippet to demonstrate the issue:
console.log("'"&@#$%^&".replaceAll(/[^a-zA-z0-9]/g,""))
2
Answers
In the uppercase range there’s a typo…
A-z
instead ofA-Z
This is happening because you’re matching both
a-z
andA-z
, with a lower casez
instead of upper caseZ
. Try the following: