skip to Main Content

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


  1. In the uppercase range there’s a typo… A-z instead of A-Z

    Login or Signup to reply.
  2. This is happening because you’re matching both a-z and A-z, with a lower case z instead of upper case Z. Try the following:

    console.log("'"&@#$%^&".replaceAll(/[^a-zA-Z0-9]/g,""))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search