6

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?

2 Answers 2

7

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++);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

5
"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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.