Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?
Thank you.
Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?
Thank you.
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
"someone@example.com".split('@')[0]
username:
"someone@example.com".replace(/^(.+)@(.+)$/g,'$1')
server:
"someone@example.com".replace(/^(.+)@(.+)$/g,'$2')
string.split(separator, limit) is the method you want
"someone@example.com".split("@")[0]
var email = "someone@example.com";
var username = email.substring(0,email.indexOf('@'))