我想使用现代 JavaScript 语法检索一个人名字和姓氏的首字母。目前,我可以正确检索名字的第一个字母和姓氏的第一个字母。
我的问题是,如果没有“of”这个词,我就无法检索它。
这是我的 Jsfiddle 链接 ----> 点击这里
代码:
/* const name = "Joshua Jones of USA"; */
const name = "William Sanders";
/* const name = "Grey Charles"; */
function getUserInitials(name) {
return /^(.).+([A-Z])\w+\sof\s.+$/.exec(name).slice(1, 3).join('');
}
console.log(getUserInitials(name));
不确定您到底想做什么,但这解决了所示的测试用例:
const names = ["Joshua Jones of USA", "William Sanders", "Grey Charles"];
function getUserInitials(name) {
return name.split(' ').map(w => w.charAt(0).toUpperCase()).splice(0,2);
}
for (const name of names)
console.log(getUserInitials(name));