[英]JavaScript: Extract parts of e-mail address and split into parts
Howto extract parts of e-mail address and split into parts and into first and last name if a dot is present like it is common in many companies? 如果像许多公司中常见的那样出现一个点,如何提取电子邮件地址的各个部分并将其分为名字和姓氏?
perry.rhodan@galaxy.net
atlan@galaxy.net
Perry
Rhodan
galaxy
net
atlan
galaxy
net
I gave my answer below using a regex and a if-clause that checks for the dot in the email. 我在下面使用正则表达式和if子句给出了答案,该子句检查了电子邮件中的点。 But maybe there is one regex to achieve the same outcome?
但是也许有一个正则表达式可以达到相同的结果?
do thi using C#: 使用C#进行操作:
Regex regex = new Regex(@"(.+)@(.+)(?=\.\w{2,})");
string texts = "perry.rhodan@galaxy.net\natlan@galaxy.net";
var list = new List<string>();
foreach (Match item in regex.Matches(texts))
{
list.AddRange(item.Groups[1].Value.Split('.').Where(v => !list.Any(l => l == v)));
list.AddRange(item.Groups[2].Value.Split('.').Where(v => !list.Any(l => l == v)));
}
foreach (var item in list)
{
Console.WriteLine(item);
}
function GetEmailParts( strEmail ){
var objParts = {
user: null,
firstName: null,
LastName: null,
domain: null,
tld: null
};
strEmail.replace(
new RegExp("^([a-z\\d._%-]+)@((?:[a-z\\d-]+\\.)+)([a-z]{2,6})$", "i"),
function( $0, $1, $2, $3 ) {
objParts.user = $1;
if ($1.length > 1) {
$1 = $1.split(".");
for(var i = 0; i < $1.length; i++){
$1[i] = $1[i].substring(0,1).toUpperCase() + $1[i].substring(1,$1[i].length);
}
objParts.firstName = $1[0];
objParts.lastName = $1[1];
};
objParts.domain = $2;
objParts.tld = $3;
}
);
return( objParts );
}
console.log(GetEmailParts("perry.rhodan@gmail.com"));
# Gives back an Object with either First and Last name sub object
# or one single user sub object if no dot is present in the email
See it in action: http://jsfiddle.net/nottinhill/0bh0vkd7/ 实际观看: http : //jsfiddle.net/nottinhill/0bh0vkd7/
I don't know if you absolutely want to write the Regexp yourself (in which case, the above answers will probably be fine). 我不知道您是否绝对想自己编写Regexp(在这种情况下,上面的答案可能会很好)。
However, since email addresses are a strange bunch to parse in general , I would recommend looking for a full-blown parser library, such as this one , if you're on nodejs. 然而,由于电子邮件地址是一个陌生的一群解析一般来说 ,我会建议寻找一个全面的解析库,比如这一个 ,如果你在的NodeJS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.