Royi Namir
Royi Namir

Reputation: 148744

Regex is not working as expected?

I have this regex :

new RegExp("^[a-z 0-9\"\-\`]+$", "ig")

and I'm testing a string which is not suppose to work : '#vc'

But it does pass the test : ( and it shouldn't (#))

new RegExp("^[a-z 0-9\"\-\`]+$", "ig").test('#vc') //true

But if I remove either \" or \- or \`, it does work ( and test fails as it should).

What am I doing wrong ?

My regex simply search for English , numbers , space , ["],[-][ and [`]

Upvotes: 3

Views: 114

Answers (1)

nhahtdh
nhahtdh

Reputation: 56829

If you use RegExp constructor, you need to double up the escaping, since there are 2 layers of escaping: escaping in JavaScript string literal and escaping in the regex syntax.

However, in your case, it is possible to write a regex without escaping at all.

In your case, you can just use literal RegExp, in which you only have to care about escaping in regex syntax, and escaping for any / that appears in the regex (since / is used as delimiter for literal RegExp:

/^[a-z 0-9"\-`]+$/gi

Another way is:

/^[a-z 0-9"`-]+$/gi

You don't need to escape dash - if it is the last in a character class. This way, you don't need to confuse yourself with all the escaping.

Or if you still want to use RegExp constructor, you need to double up the escape to specify \ in the string:

new RegExp('^[a-z 0-9"\\-`]+$', "ig")

Or just use the other version where - is specified last in the character class:

new RegExp('^[a-z 0-9"`-]+$', "ig")

Note that I change the string quote from " to ' to avoid having to escape " in the string. If you for some reason prefers ", escape " at the literal string level:

new RegExp("^[a-z 0-9\"`-]+$", "ig")

As for your current regex

new RegExp("^[a-z 0-9\"\-\`]+$", "ig")

is equivalent to

/^[a-z 0-9"-`]+$/gi

As you can see a character range from " to ` is included, which means all characters with ASCII code from 0x22 to 0x60 are included, and # happens to be in the range.

To check whether the pattern is what you want, you can always call source property of the regex to obtain the source string of the regex.

Upvotes: 5

Related Questions