0

How would I format a number like: (99) 9999-9999 into: 9999999999 using angularjs? someone told me to use phoneformat.js but I don't know how to implement it in my project

Stack two
  • 531
  • 2
  • 12
  • 27
  • I would start with the [Install Instructions](https://github.com/albeebe/phoneformat.js#install) and then move down to [FAQ](https://github.com/albeebe/phoneformat.js#faq). Finally, check out the [Demo](https://github.com/albeebe/phoneformat.js#faq) portion. Then try it out and then we will help when you get stuck :) – KJ Price Mar 13 '15 at 20:20

4 Answers4

1

I'm not sure that you need anything special from Angular or any special libraries . . . just use the basic JS .replace() method and a little regex:

var sPhoneNum = "(99) 9999-9999";
var sFormattedPhoneNum = sPhoneNum.replace(/\D/g, "");
// sFormattedPhoneNum equals "9999999999"

The regular expression /\D/g matches all non-numeric characters, so it will strip out everything but the numbers.

talemyn
  • 7,822
  • 4
  • 31
  • 52
  • 1
    I guess the angular way would be just to put this in a filter :) but I agree this would be the best and easiest way... no need to start including external files just to strip down all none numeric...this is the correct answer, just put it in a custom filter and puff... its angularized:) – Jony-Y Mar 13 '15 at 20:32
  • Yeah, good point . . . you do actually have to plug it into your angular code for it to work. :) But, yeah, this is pretty simple formatting logic . . . certainly no need for any heavy-duty tools to get it done. – talemyn Mar 13 '15 at 20:58
  • 1
    yup:) thats why I up voted the answer :) I just added the filter answer below should he want a filter... – Jony-Y Mar 13 '15 at 21:04
1

so like talemyn said... the solution is simply to remove the unwanted char... the angular way to do it is via filter I guess... this is a jsfillde with an example...

myApp.filter('phoneToNum', function() {
    return function(input, scope) {
        return input.replace(/\D/g, "");
    }
});

now if you also want to revert it... use phone filter

Community
  • 1
  • 1
Jony-Y
  • 1,579
  • 1
  • 13
  • 30
0

Try this:

formatLocal('US', phoneNumber)

Greg Lafrance
  • 768
  • 1
  • 7
  • 18
0

I had an input field where I needed to get phone number from users but only the digits so that it's easy to index using phone number in the database. I used .replace on ng-keyup, so the non-digit characters gets removed as the user types.

in html

<input ng-keyup="formatNum()" ng-model='data.phone' placeholder="Phone Number" />  

in controller

$scope.formatNum = function() {
 if ($scope.data.phone)
      $scope.data.phone = $scope.data.phone.replace(/\D/g, "");
};
Udeep
  • 1
  • 2