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!

1
  • Escape the backslashes. '/^[1-9][0-9]{3}\\s?([a-zA-Z]{2})?$/' Commented Jan 10, 2016 at 12:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good morning, Teej. Yeesh. Read right past 'em. If you think any of my now-deleted answer would be useful to add, feel free to grab it.
Thanks! That helped a lot :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.