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+sofs.+$/.exec(name).slice(1, 3).join('');
}
console.log(getUserInitials(name));
2
Answers
Not sure what exactly you’re trying to do, but this solves the shown test cases:
If this doesn’t satisfy your requirements, then please elaborate on those.
If your test cases cover all possible formats, you can either improve your regexp:
or you can split by "of" first, and then split by whitespaces: