如何使用 javascript 从电子邮件地址中提取用户名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7266608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:30:51  来源:igfitidea点击:

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

javascriptemail

提问by VvDPzZ

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

给定以下电子邮件地址[email protected]如何使用javascript 从地址中提取某人?

Thank you.

谢谢你。

回答by epascarello

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

JSPerf 测试

回答by qingbo

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

回答by Andrew D.

username:

用户名:

"[email protected]".replace(/^(.+)@(.+)$/g,'')

server:

服务器:

"[email protected]".replace(/^(.+)@(.+)$/g,'')

回答by Devdutta Natu

var email = "[email protected]";

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

回答by kmcc049

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

string.split(separator, limit) 是你想要的方法

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

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