Search code examples
meteormeteor-helper

Formatting US zip codes with leading zeros in a Meteor helper


I have a collection in Meteor that has an imported csv file with a Zip Code field. The problem is when I print out a document from a query, it will print a zip like 04191 to 4191.

....
{{#each Query}}
<p>{{Zip}</p>
{{/each}}
....

I'd need something like:

....
{{#each Query}}
<p>{{Zip.toString()}</p>
{{/each}}
....

Solution

  • Here's a generic zip code helper:

     Template.registerHelper('formatZip',function(zip){
       var pad="00000";
       return (pad+zip).slice(-5); // 5 digit zips only!
     });
    

    You can use this from any template in your app with:

    {{formatZip Zip}}
    

    Assuming Zip contains the zip code you wish to format.

    With props to https://stackoverflow.com/a/9744576/2805154 - this answer merely reformulates that answer for Meteor.