I wanted to retrieve the first letters of a person’s first name and last name using modern JavaScript syntax. Currently, I’m able to retrieve the first letter of the first name and the first letter of the last name correctly.
My problem is that if there’s no "of" word, I can’t retrieve it.
Here’s my Jsfiddle link —-> CLICK HERE
CODE:
/* 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));
>Solution :
Not sure what exactly you’re trying to do, but this solves the shown test cases:
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));
If this doesn’t satisfy your requirements, then please elaborate on those.