Format Number Based on JavaScript / jQuery Formatting String

Let's say i have

  • format string "XXX - XXX - XXXX" (for formatting a phone number) or any other format string in which X represents a number
  • I want to keep formatting in a format string (interval, dash, etc.), but exchange each X for a number and discard all formatting in the original string

Examples:

  • Input: "abc + d (123) 4567890", String format: "XXX - XXX - XXXX", Output: "123 - 456 - 7890"
  • Entering "abc 1 2 3 4567890", Format string: "X: X! XXXXX, XXX", Exit: "1: 2! 34567.890"
  • Entering "1234567890", Format string: "(XXX) XXX-XXXX", Exit: "(123) 456-7890"

I think I could capture a number, iterating over the original string (the foreach character in '0123456789'), but I'm not sure how I can elegantly put them together in the right format. Maybe there is a jQuery function that does this already?

+6
javascript jquery formatting string-formatting
source share
2 answers

Here is one way to do this:

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++); }); } 
+5
source share
 "abc+d(123)4567890" .replace(/\D/g, "") .replace(/(\d{3})(\d{3})(\d{4})/, "$1 - $2 - $3") 

First we remove the non-digital characters (\ D), then group them and finally use the groups in our replacement text.

+4
source share

All Articles