1

I'm looking a way to reformat a phone number for display in Javascript. Here's an example of some of the data:

00-22 345 991

555922134

12450-123948

I want to reformat the number to the following 3 length format like: 555-922-134

Assuming that dashes and spaces can be ignored and the last two blocks can be a length of 2 like: 002-234-59-91 or 124-501-349-48

goateee25
  • 183
  • 1
  • 2
  • 10

2 Answers2

3

You can use a regex with lookahead.

The Positive Lookahead looks for the pattern after the equal sign, but does not include it in the match.

x(?=y)

Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.

For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.

function format(s) {
    return s.toString().replace(/\D/g, '').replace(/\d{2,3}(?=..)/g, '$&-');
}

console.log(format('00-22 345 991'));
console.log(format('555922134'));
console.log(format('12450-123948'));
console.log(format(123456789));
console.log(format(12345678901));
console.log(format(1234567));
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Good evening! :)

This have been answered in a previous thread. :)

Insert hyphens in javascript

Hope this helps out - have a good night :)

Community
  • 1
  • 1