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
4 Answers
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.
3 Comments
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
Comments
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, "");
};