Let's say I have a
Examples:
I'm thinking I could grab the number by iterating through the source string (foreach character in '0123456789') but I'm not sure how I can then put this together elegantly to the right format. Maybe there is a jQuery function which does this already?
Here's one way to do it:
function formatPhoneNumber(input, format) {
// Strip non-numeric characters
var digits = input.replace(/\D/g, '');
// Replace each "X" with the next digit
var count = 0;
return format.replace(/X/g, function() {
return digits.charAt(count++);
});
}
"abc+d(123)4567890"
.replace(/\D/g, "")
.replace(/(\d{3})(\d{3})(\d{4})/, "$1 - $2 - $3")
First we remove the non-digits (\D), then we group them, and finally we use the groups in our replacement text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With