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 is “of” word, I can’t retrieve it.
Code
const names = ["Joshua Jones of USA", "William Sanders", "Grey Charles", "Carlos James Thomas of Russia", "Peter John Parker", "Juan Carlos Tenaz Lopez III of Spain"];
function getUserInitials(name) {
return name.split(' ').map(w => w.charAt(0).toUpperCase()).splice(0,2);
}
for (const name of names)
console.log(getUserInitials(name));
Expected Output
JJ, WS, GC, CT, PP, JL
In my solution, I completely split the name along the conjunctions and keep only the beginning. Subsequently, at every word consisting of multiple capital letters, I also separate them. From these names, I concatenate the first and last capital letters and return the result.
function getUserInitials(name) {
// Clean up the name: remove titles, conjunctions, and punctuation
// Carlos James Thomas of Russia ---> Carlos James Thomas
name = name.replace(/(?:b(?:of|the|and|in|on|at|for|with)b|[,.]).*$/gi, '');
// Remove all-uppercase words (e.g., III)
// Juan Carlos Tenaz Lopez III, Mexico ---> Juan Carlos Tenaz Lopez
name = name.replace(/b[A-Z]+b/g, '');
// Remove whitespaces
name = name.trim();
// Get names
const words = name.split(' ');
// Get first char from First and Last name
let result = '';
result += words[0].charAt(0).toUpperCase();
result += words[words.length - 1].charAt(0).toUpperCase();
return result;
}
// Test cases
const names = [
"Joshua Jones of USA",
"William Sanders",
"Grey Charles",
"Carlos James Thomas of Russia",
"Peter John Parker",
"Juan Carlos Tenaz Lopez III of Spain",
];
for (const name of names) {
console.log(getUserInitials(name));
}