javascriptemail

How can I extract the user name from an email address using javascript?


Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?

Thank you.


Solution

  • Regular Expression with match

    with safety checks

    var str="someone@example.com";
    var nameMatch = str.match(/^([^@]*)@/);
    var name = nameMatch ? nameMatch[1] : null;
    

    written as one line

    var name = str.match(/^([^@]*)@/)[1];
    

    Regular Expression with replace

    with safety checks

    var str="someone@example.com";
    var nameReplace = str.replace(/@.*$/,"");
    var name = nameReplace!==str ? nameReplace : null;
    

    written as one line

    var name = str.replace(/@.*$/,"");
    

    Split String

    with safety checks

    var str="someone@example.com";
    var nameParts = str.split("@");
    var name = nameParts.length==2 ? nameParts[0] : null;
    

    written as one line

    var name = str.split("@")[0];
    

    Performance Tests of each example

    JSPerf Tests