Categories
JavaScript Answers

How to Check for Canadian Postal Code Strings with JavaScript?

Spread the love

Sometimes, we want to check for Canadian postal code strings with JavaScript.

In this article, we’ll look at how to check for Canadian postal code strings with JavaScript.

Check for Canadian Postal Code Strings with JavaScript

To check for Canadian postal code strings with JavaScript, we can create our own regex and use it.

For instance, we can write:

const regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;

console.log(regex.test('45464'))
console.log(regex.test('A1A 1A1'))

to create the regex where we check for 2 groups of 3 characters where we have 1 digit in between 2 letters in the first group, and a letter is in between 2 betters in the 2nd group.

And each group of characters is separated by a space, dash, or nothing.

^ indicates the beginning of the string.

[A-Za-z] matches upper and lower case letters.

d matches digits.

[ -]? optionally matches a space or dash.

$ indicates the end of the string.

Therefore, the first console log logs false and the 2nd one logs true .

Conclusion

To check for Canadian postal code strings with JavaScript, we can create our own regex and use it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *