鳳凰求蠱
2022-10-08 15:02:54
我想對名字和姓氏進行排序,我的問題是當用戶有多個名字時,例如:'Michael Jordan Atticus Smith'基本上,史密斯是那里的姓氏,我如何用它分割名字和姓氏?我想要的結果是:'Michael Jordan Atticus' 'Smith'
1 回答

慕的地10843
TA貢獻1785條經驗 獲得超8個贊
let str = 'Michael Jordan Atticus Smith';
console.log( ex1(str) );
console.log( ex2(str) );
console.log( ex3(str) );
function ex1(str) {
let names = str.match(/(.*?)\s(\S+)$/); // (1)
return [ names[1], names[2] ];
}
function ex2(str) {
let names = str.split(" ");
return [names.pop(), names.join(" ")].reverse(); // (2)
}
function ex3(str) {
let last = ""
str = str.replace(/\s(\S+)$/, function(full_match, parenthesis_1) {
last = parenthesis_1;
return "";
});
return [str, last];
}
(1) match()
返回匹配字符串的數組。另外,請參閱RegEx 小抄表
(2)數組pop()
方法移除,并返回最后一個元素。代碼從左到右執行,因此,第二個names.join(" ")
收集了左邊的 3 個名稱。
添加回答
舉報
0/150
提交
取消