Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  104] [ 1]  / answers: 1 / hits: 36303  / 13 Years ago, thu, september 1, 2011, 12:00:00

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



Thank you.


More From » email

 Answers
52

Regular Expression with match



with safety checks



var [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 [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 [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


[#90318] Tuesday, August 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
;