Question

I am using Handlebars to compile a template that returns JSON data. My issue is that I would like to create a tel link to the phone numbers which are displayed, but the format they are being returned in is: (XXX) XXX-XXXX

I know you can register a helper to take a string of numbers and then format them, but is there any way to do the reverse(strip out any non-numeric characters/spaces)?

This is the helper which does the inverse of what I am trying to do:

Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
  phoneNumber = phoneNumber.toString();
  return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
});

Thanks!

Was it helpful?

Solution

Sure, you can just use a regular expression to strip out anything that's not a digit:

Handlebars.registerHelper("unformatPhoneNumber", function(phoneNumber) {
    return phoneNumber.replace(/\D/g,'');
});

OTHER TIPS

Nevermind, figured it out based on a non-handlebars answer.

Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
    return phoneNumber.replace(/\D/g,'');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top