Question

I am using following regex to convert digits into phone format.

telephoneNumber = '1234567890';
var number = telephoneNumber.replace(/\D/g,''); 
newNumber = number.replace(/^(\d{3})(\d{3})(\d{4})$/, '($1)$2-$3'); // (123)456-7890

Problem is that if telephoneNumber.length is greater than 10 then it does nothing. I want to add extra digits in the end of the phone number.

For example:

change 1234567890 to (123)456-7890
change 1234567890111 to (123)456-7890111

What should I change in above regex.

Thanks.

Was it helpful?

Solution

Try changing the last line to this: newNumber = number.replace(/^(\d{3})(\d{3})(\d{4,})$/, '($1)$2-$3');

I just added a comma after the \d{4 this tells it to take 4 or more digits.

Also, I often use this site to test out my regex's: http://gskinner.com/RegExr/ It's VERY handy.

OTHER TIPS

The only reason I can see you wanting to use a Regex is for validation, however if you're just trying to format the string to a phone number, why not just use a Javascript Phone Number Formatter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top