1

I'm getting a syntax error in this simple javascript code. I just want to check the atring on a pattern. Can any one tell me what is wrong?

var a = 'test@server.com';
var pattern = [a-zA-Z0-9_]+[.[a-zA-Z0-9]+]*@[a-zA-Z0-9_]+[.[a-zA-Z]+]+;
console.log('The comparison is ',a.match(pattern));

Thanks.

Juanillo
  • 875
  • 2
  • 11
  • 17
  • Your pattern is not a regular expression. It is just a bunch of characters and it will create a syntax error. Regular expressions literals start and end with `/`. – Felix Kling Aug 04 '11 at 10:02

3 Answers3

4

Try

var pattern = /[a-zA-Z0-9_]+[.[a-zA-Z0-9]+]*@[a-zA-Z0-9_]+[.[a-zA-Z]+]+/;

Patterns are usually delimited by //. See RegExp on MDC.

Nivas
  • 18,126
  • 4
  • 62
  • 76
  • Yeah, with "/" the syntax error disapperas, the strange thing is that matches return null. I think it should match the pattern – Juanillo Aug 04 '11 at 10:05
  • check the usage of the square brackets `[` and `]`... it is strange... I guess you want to have `[.a-zA-Z0-9]` instead of `[.[a-zA-Z0-9]+]` . But you should also be aware that the correct regexp for an email address is even more complex. see http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses for more details. BTW: `/[a-zA-Z0-9_]+[.a-zA-Z0-9]*@[a-zA-Z0-9_]+[.a-zA-Z]+/` matches... – rdmueller Aug 04 '11 at 10:11
1

try

 var pattern = /^[a-zA-Z0-9_]+[.[a-zA-Z0-9]+]*@[a-zA-Z0-9_]+[.[a-zA-Z]+]+$/;
nirmus
  • 4,913
  • 9
  • 31
  • 50
0

you have no delimiter on the pattern. Have you tried

var pattern = '[a-zA-Z0-9_]+[.[a-zA-Z0-9]+]*@[a-zA-Z0-9_]+[.[a-zA-Z]+]+';

?

rdmueller
  • 10,742
  • 10
  • 69
  • 126