0

I'm trying to validate email addresses in javascript, I tried this

/[A-Za-z0-9_\-]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+/

but it matched the input "b@aaa", where the middle "a" letter should be a dot to match. and tried not to escape the dot like this:

/[A-Za-z0-9_\-]+\@[A-Za-z0-9_\-]+.[A-Za-z0-9_\-]+/

and it matched the input too.

Megamind Saiko
  • 659
  • 7
  • 13

1 Answers1

1

I think you need 2 backslashes:

/[A-Za-z0-9_\-]+\@[A-Za-z0-9_\-]+\\.[A-Za-z0-9_\-]+/

David Xu
  • 5,555
  • 3
  • 28
  • 50
  • Thanks, adding another backslash worked (although I don't know why :) ) – Megamind Saiko May 02 '14 at 19:08
  • 1
    Because regex is also a type of string and \ has special meaning in string, so you need 2 of them to actually create a \. – David Xu May 02 '14 at 19:09
  • but like this, other backslashes should be doubled too, ^[A-Za-z0-9_\\-]+\\@[A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+" and if it worked without doubling, it worked as it doesn't need escaping (the @ sign) and the hyphen is the last item in the square brackets, right? – Megamind Saiko May 02 '14 at 19:30