[Javascript] using regular expression to clean a phone number field

Hassan Schroeder hassan at webtuitive.com
Fri Mar 7 12:36:02 CST 2003


Michael Dougherty wrote:
> I would like to put clean phone numbers into my database. 

> phoneFormatUnknown = document.all["Phone"].value

Unless this is an intranet, you might want to reconsider the
IE-specific "document.all", but ...

> ex: (123) 123-1234		==> 1231231234
> ex: 123.123.1234 			==> 1231231234
> ex: 1(123) 123-1234 		==> 11231231234
> ex: 1-123-123-1234 ext 123	==> 11231231234123
> ex: 1-800-You're number 1	==> 18001 (OK that the output is as useless as the
> input)

<script type="text/javascript">
function numericOnly(str)
{
     var nums = /[^\d]/g; /* anything that's not 0-9 */
     return str.replace(nums, ""); /* replace with null string */
}
</script>

<input type="text" name="phone" onchange="this.value=numericOnly(this.value);" />

> bonus: 1-800-OKCOMPAQ		==> 180065266722 (i don't care how ugly the regexp is
> :)

I'm in the middle of an OS install and a couple of other things, so
maybe I'll come back to that one :-)

HTH!
-- 
Hassan Schroeder ----------------------------- hassan at webtuitive.com
Webtuitive Design ===  (+1) 408-938-0567   === http://webtuitive.com

                           dream.  code.






More information about the Javascript mailing list