0

I came across this problem when trying to stop a single quote (') being matched in a string.

Here is a snippet from a console session in Chrome. Params is the regex I'm trying to match (no single or double quotes should be allowed?). I would have expected the first two execs to find a match and the second two to fail due to the single quote in the text.

Suppose this raises two questions:

  1. Why does the literal behave differently to the variable?
  2. Why does the third exec find a match when there should be no match on the single quote?

thanks

> params
> 
>> "^[a-zA-Z0-9 -_/&,()\[\];:+~.!\\]*$"
> 
> 
> new RegExp(params).exec("some string")
>> ["some string"]
> 
> new RegExp("^[a-zA-Z0-9 -_/&,()\[\];:+~.!\\]*$").exec("some string")
>> null
> 
> 
> new RegExp(params).exec("some string's")
>> ["some string's"]
> 
> new RegExp("^[a-zA-Z0-9 -_/&,()\[\];:+~.!\\]*$").exec("some string's")
>> null
anubhava
  • 761,203
  • 64
  • 569
  • 643
PaulB
  • 23,264
  • 14
  • 56
  • 75

1 Answers1

1
^[a-zA-Z0-9 _/&,()[];:+~.!\-]*$

Always keep - at end or escape it to avoid forming an invalid range.

Here - forms a range from space 32 to _ 95.' is 39 so it falls in between that invalid range and so a match.

vks
  • 67,027
  • 10
  • 91
  • 124