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

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


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

var email = "[email protected]";

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