Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Format Phone Numbers

Status
Not open for further replies.

celley

Programmer
Jul 31, 2000
54
A2
i am writing a phone number format in javascript. i have the actual
formatting part working fine (if one enters no (,),-, etc.). i decided
to delve into regular expressions to strip out the punctuation
characters. well, it isn't doing what it is supposed to do and i have
no idea how to make it do what it needs to do. i am going on scraps
from MSDN and some help i got the other day on a js function, which
doesn't help much. anyone help? [sig]<p>Chad Elley<br><a href=mailto:celley@gobcg.com>celley@gobcg.com</a><br>[/sig]
 
You can either strip special puntuation characters:
Code:
s=s.replace(/[()-,. ]*/, '')
of you can strip all except numbers:
Code:
s=s.replace(/\D*/, '')
or equivalent:
Code:
s=s.replace(/[^0-9]*/, '')
asterisk (*) at the end of patterns needed to slitly faster processing. [sig]<p>Michael Dubner<br>Brainbench MVP/HTML+JavaScript<br>
[/sig]
 

If you send the phone number through parseInt() it will remove all the formatting for you:

Code:
var numberFromInput = "+1 555 123 4567";
var numberWithoutFormatting = parseInt(numberFromInput,10);

By adding the radix of 10 as a second parameter, you specify base 10 for the result. This is important for correct cross-browser support as well as avoiding unexpected results.

Once you have all non-numberic formatting removed this way, you can convert it back to a string and then use string manipulation to re-format it nicely again.

Cheers,
Jeff

 

Just thought it would make interesting reading for those doing telephone formatting [smile] And it's a slow day at work today!

Jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top