Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Thank you.

like image 346
VvDPzZ Avatar asked Sep 01 '11 06:09

VvDPzZ


People also ask

Can an email contain JavaScript?

Web browsers display interactive, dynamic content, and they update often. But interactive elements like Flash, JavaScript, or HTML forms won't work in most email inboxes.


1 Answers

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

like image 85
epascarello Avatar answered Sep 21 '22 12:09

epascarello