Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2003
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Regular Expressions

    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

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    /^\(?(\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?
    Last edited by liorean; 05-09-2004 at 09:02 PM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •