...

View Full Version : Regular Expressions



Hirameck
05-09-2004, 09:34 PM
Hi!

I need to convert phone number.
If the phone number 1234567890 is entered, then on submit the number should be converted to (123)456-7890.
This what I got sofar.

function convert_telephone1() {
var temp7 = document.form1.telephone1.value;
temp7 = temp7.replace(temp7, /^\(?(\d{3})\)?[\.\-\/]?(\d{3})[\.\-\/]?(\d{4})$/); // Phone no. - Validation
document.form1.telephone1.value = temp7;
}
<input type="text" name="telephone1">
<input type="button" onClick="convert_telephone1();" value="Validate Phone number1">

* Could you also explain where I went wrong.

THANKS :mad:

liorean
05-09-2004, 09:59 PM
/^\(?(\d{3})\)?[\.\-\/]?(\d{3})[\.\-\/]?(\d{4})$/
To dissect this:
/^ - begin regex and match beginning of string
\(? - match zero or one opening paren
(\d{3}) - match three digits and capture the match
\)? - match zero or one closing paren
[\.\-\/]? - match zero or one fullstop, backslach or slash
(\d{3}) - match three digits and capture the match
[\.\-\/]? - match zero or one fullstop, backslach or slash
(\d{4}) - match four digits and capture the match
$/ - match end of string and end regex


However, where you went wrong:
String.prototype.replace(regex,stringorcallback)
you got the order of the string and regex wrong.

Also, what do you want to do, really? Do you really want to replace that string?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum