0

I have the following problem, I use this regex in my ruby code, it works perfectly fine in ruby:

^[a-z0-9]+[a-z0-9\.\-_]*$

When I try to match it via JavaScript in my jquery:

$("#foo").val().match("^[a-z0-9]+[a-z0-9\.\-_]*$"))

the . and _ works but not for the -, it simply doesn't match in this case but it should.

Any ideas why this happens? Its already escaped.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Calmon
  • 583
  • 5
  • 18
  • 2
    The hyphen is not matched because it is not escaped properly, and creates a range. See [a similar issue](http://stackoverflow.com/questions/32740108/js-regex-allowing-incorrect-characters/32740493#32740493). The best way is to use a regex literal notation: `/^[a-z0-9]+[a-z0-9._-]*$/`. – Wiktor Stribiżew Feb 22 '16 at 11:21
  • 1
    I only found this http://stackoverflow.com/questions/3697202/including-a-hyphen-in-a-regex-character-bracket but its not my problem, because I already use an escaped version. edit: ok understand, I shouldn't use any escapes. It tried and it works fine. Thanks! – Calmon Feb 22 '16 at 11:21
  • You're not escaping the regex, you're escaping the string. Wiktor is right; if you want to stick with the string instead of the regex literal you need to use `"^[a-z0-9]+[a-z0-9\\.\\-_]*$"` (or re-order the characters in the class like so: `"^[a-z0-9]+[a-z0-9._-]*$"` - the . is not "any" character inside the []) – Lucero Feb 22 '16 at 11:26

0 Answers0