views:

105

answers:

2

Let's say I have a

  • format string "XXX - XXX - XXXX" (to format a phone number), or any other format string in which X stands for a number
  • I want to preserve the formatting in the format string (spacing, dashes etc.), but exchange each X for a number and drop all formatting in the source string

Examples:

  • Input: "abc+d(123)4567890", Format String: "XXX - XXX - XXXX", Output: "123 - 456 - 7890"
  • Input "a b c 1 2 3 4567890", Format String: "X:X!XXXXX,XXX", Output: "1:2!34567,890"
  • Input "1234567890", Format String: "(XXX)XXX-XXXX", Output: "(123)456-7890"

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?

+1  A: 
"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.

Matthew Flaschen
Sorry I wasn't clear on that the format string may be different (e.g. could change to X-XXX-XX-XX) so it would need to be able to cope with the format generically.
Alex
+1  A: 

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++);
    });
}
Matthew Crumley