Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Number based on Format String in JavaScript/jQuery

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?

like image 354
Alex Avatar asked Jul 11 '10 18:07

Alex


2 Answers

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++);
    });
}
like image 154
Matthew Crumley Avatar answered Sep 19 '22 23:09

Matthew Crumley


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

like image 41
Matthew Flaschen Avatar answered Sep 19 '22 23:09

Matthew Flaschen