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

Given the following email address -- [email protected] -- how can I extract someone from the address using javascript?

Thank you.

Answers:

Answer

Regular Expression with match

with safety checks

var str="[email protected]";
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="[email protected]";
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="[email protected]";
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

Answer
"[email protected]".split('@')[0]
Answer

username:

"[email protected]".replace(/^(.+)@(.+)$/g,'$1')

server:

"[email protected]".replace(/^(.+)@(.+)$/g,'$2')
Answer
var email = "[email protected]";

var username = email.substring(0,email.indexOf('@'))
Answer

string.split(separator, limit) is the method you want

"[email protected]".split("@")[0]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.