0

From the backend of my application, I receive a regular expression which should be matched with a postal code in the frontend.

However, every time I convert to string into a regular expression using the RegExp class, I get another regular expression which doesn't match my postal code anymore.

This is the code I'm currently using (copy from my console):

var str = '/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/',
exp = new RegExp(str);

// Returns null
'1055AA'.match(exp);

// The code below does work though...
// Returns: ["1055AA", "AA"]
'1055AA'.match(/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/);

Can someone help me solve this problem? Thanks!

Vernon
  • 443
  • 4
  • 23

1 Answers1

1

Your input string must not begin and end with the Regexp markers / - after all, it's a regular string, not a literal regexp. Also, since it's a regular string (and not (yet) a regexp), you need to double the backslashes as usual in a regular string.

Jongware
  • 22,200
  • 8
  • 54
  • 100