0

I am trying to validate Canadian ZIP codes using a regex in JavaScript.

This is my code:

var RegEx = new RegExp("/^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d/");        
console.log(RegEx.test("G0A 1L0"));

I get false even though the ZIP code is valid. What's wrong with my regex?

fenceop
  • 1,439
  • 3
  • 18
  • 29
ding dang
  • 19
  • 1
  • 4
  • Marked as duplicate of `Canadian postal code validation`, meanwhile, he made a delimiter error, assuming a a regex literal variant was to be used in the string passed to the constructor of RegExp(). Does anybody read past the title ? The title is inaccurate, but still .. –  Jun 30 '15 at 20:41

1 Answers1

1

Try taking out the / at the beginning and end of the string.

You'll also need to double up the \ characters; otherwise, javascript interprets the string "\d" as simply d.

Assuming the entire string has to match, you probably want an end-of-line anchor at the end of the pattern as well.

var RegEx = new RegExp("^[A-Za-z]\\d[A-Za-z][ -]?\\d[A-Za-z]\\d$");
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151