How can I extract the user name from an email addr

2019-01-06 17:53发布

问题:

Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?

Thank you.

回答1:

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



回答2:

"someone@example.com".split('@')[0]


回答3:

username:

"someone@example.com".replace(/^(.+)@(.+)$/g,'$1')

server:

"someone@example.com".replace(/^(.+)@(.+)$/g,'$2')


回答4:

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

"someone@example.com".split("@")[0]



回答5:

var email = "someone@example.com";

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