This needs testing, but perhaps something in this direction:
// Regex extended to include possible "<", ">", and "," at end
var re = /^<?[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*>?,?$/,
name = [], // Temporary placeholder for name
rec = [], // Records
inp = email.split(/[ ]+/) // Split input on space(s)
;
for (i = 0; i < inp.length; ++i) {
if (re.test(inp[i])) { // Check if valid email
rec.push({
name: name.join(' '), // Name
email: inp[i].replace(/[<>,]/g, '') // Remove <, > and ,
});
name = [];
} else {
name.push(inp[i]) // Not valid e-mail, add to name array.
}
}
Sample fiddle with modifications
You could skip the creation of result array, but then, why do the same job on the server? As anything not an e-mail would be pushed as a name the only fail criteria are if name
has a length greater then 0
at end of loop, or the records array is empty.
The regexp needs work. But concept could be a start. It would for example validate:
Some name <some@example.net
|
+--- missing >
etc. Though that one in particular could simply be a nicety if you do not want to be strict.
As there are no validation on name, anything not validating as e-mail, would be a name. If you need to validate name as well you could have a look at this or similar:
An alternative to validating the name is to remove unwanted characters, at least in the ASCII range. For example:
re_name = /^'|[\x00-\x1f\x21-\x26\x28-\x2b\x2f-\x40\x5b-\x5f\x7b-\x7e]/g
' At start of name
0x00 - 0x1f NUL -> US
0x21 - 0x26 ! -> &
0x28 - 0x2b ( -> +
0x2f - 0x40 / -> @
0x5b - 0x5f [ -> _
0x7b - 0x7e { -> ~
And then do:
name : name.join(' ').replace(re_name, ''),
Sample input:
var email =
'LastnameA, FirstnameA <nameA@example.net>, ' +
'FirstnameB LastnameB <nameB@example.net, ' + // missing >
'LastnameC <nameC@example.net>, ' +
'LastD NameD, MiddleD NameD, FirstD NameD nameD@example.net ' +
'"FirstE E. LastnameE" <nameE@example.net>, ' +
'nameF@nonamebeforeme.example.net ' +
'Połącz Słońce w Mózu <plz@example.net> ' +
'L33t Spiiker /good/mofo]] <l33t@hotmail.com> ' +
'Moot @m Email'
;
Output:
8 records => [
{
"name": "LastnameA, FirstnameA",
"email": "nameA@example.net"
},
{
"name": "FirstnameB LastnameB",
"email": "nameB@example.net"
},
{
"name": "LastnameC",
"email": "nameC@example.net"
},
{
"name": "LastD NameD, MiddleD NameD, FirstD NameD",
"email": "nameD@example.net"
},
{
"name": "FirstE E. LastnameE",
"email": "nameE@example.net"
},
{
"name": "",
"email": "nameF@nonamebeforeme.example.net"
},
{
"name": "Połącz Słońce w Mózu",
"email": "plz@example.net"
},
{
"name": "Lt Spiiker goodmofo",
"email": "l33t@hotmail.com"
}
]
Leftovers: "Moot @m Email"