這需要測試,但也許事情朝這個方向:
// Regex extended to include possible "<", ">", and "," at end
var re = /^<?[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-][email protected][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
你可以跳過結果數組的創建,但隨後,爲什麼做同樣的工作在服務器上?由於任何不是電子郵件都會被作爲名字推送,唯一的失敗標準是name
在循環結束時的長度大於0
,或者記錄數組爲空。
正則表達式需要工作。但概念可能是一個開始。它會例如驗證:
Some name <[email protected]
|
+--- missing >
等等。雖然如果你不想嚴格,特別是可以簡單地是一個很好。
由於名稱上沒有驗證,所以任何不作爲電子郵件驗證的都是名稱。如果您需要驗證的名字以及你可以看看這個或類似:
來驗證名稱的替代方法是刪除不需要的字符,至少在ASCII範圍內。例如:
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 { -> ~
然後執行:
name : name.join(' ').replace(re_name, ''),
樣品輸入:
var email =
'LastnameA, FirstnameA <[email protected]>, ' +
'FirstnameB LastnameB <[email protected], ' + // missing >
'LastnameC <[email protected]>, ' +
'LastD NameD, MiddleD NameD, FirstD NameD [email protected] ' +
'"FirstE E. LastnameE" <[email protected]>, ' +
'[email protected] ' +
'Połącz Słońce w Mózu <[email protected]> ' +
'L33t Spiiker /good/mofo]] <[email protected]> ' +
'Moot @m Email'
;
輸出:
8 records => [
{
"name": "LastnameA, FirstnameA",
"email": "[email protected]"
},
{
"name": "FirstnameB LastnameB",
"email": "[email protected]"
},
{
"name": "LastnameC",
"email": "[email protected]"
},
{
"name": "LastD NameD, MiddleD NameD, FirstD NameD",
"email": "[email protected]"
},
{
"name": "FirstE E. LastnameE",
"email": "[email protected]"
},
{
"name": "",
"email": "[email protected]"
},
{
"name": "Połącz Słońce w Mózu",
"email": "[email protected]"
},
{
"name": "Lt Spiiker goodmofo",
"email": "[email protected]"
}
]
Leftovers: "Moot @m Email"
你能告訴我們你的」至今爲止這個要求已經嘗試過了嗎?這有助於瞭解你在哪裏*特別*被卡住了。 – Jeroen