简体   繁体   中英

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?

Input 1

perry.rhodan@galaxy.net

Input 2

atlan@galaxy.net

Wanted Output 1

Perry 
Rhodan
galaxy
net

Wanted Output 2

atlan
galaxy
net

I gave my answer below using a regex and a if-clause that checks for the dot in the email. But maybe there is one regex to achieve the same outcome?

do thi using 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/

I don't know if you absolutely want to write the Regexp yourself (in which case, the above answers will probably be fine).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM