Skip to content

JS Regex match Canadian postal code from string

I would like to find the alphanumeric canadian postal code from a string. A string such as H9B2R1|taco|salsa|taco or if encoded, H9B2R1%7Ctaco%7Csalsa%7Ctaco. The result I’m looking for is the trimmed postal code before any special characters and/or non-alphanumeric values. How to I use split or regex to parse/match this to return H9B2R1 ? I searched stackoverflow for a question like this, but didn’t find any.



try this

"H9B2R1|taco|salsa|taco".match(/w+/)[0] //returns H9B2R1
"H9B2R1%7Ctaco%7Csalsa%7Ctaco".match(/w+/)[0] //returns H9B2R1

//or using split method

"H9B2R1|taco|salsa|taco".split(/W/)[0] //returns H9B2R1
"H9B2R1%7Ctaco%7Csalsa%7Ctaco".split(/W/)[0] //returns H9B2R1
User contributions licensed under: CC BY-SA
8 People found this is helpful