function getUserInitials(name) {
// Clean up the name: remove titles, conjunctions, and punctuation
// Juan Carlos Tenaz Lopez III of Spain ---> Juan Carlos Tenaz Lopez III
name = name.replace(/(?:\b(?:of|the|and|in|on|at|for|with)\b).*$/gi, '');
// Remove Jr. / Sr.
name = name.replace(/\b(?:Jr|Sr)\.?\b/g, '').replace(/\s*\./g, '');
// Remove Roman numerals
// Juan Carlos Tenaz Lopez III ---> Juan Carlos Tenaz Lopez
// Juan Carlos Tenaz Lopez III Another Name ---> Juan Carlos Tenaz Lopez Another Name
name = name.replace(/\b(?:M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))\b/g, '');
// Just tip: After removing the Roman numerals, double spaces were left in place, so from there, we can trim the string if desired
// Juan Carlos Tenaz Lopez Another Name ---> Juan Carlos Tenaz Lopez
name = name.replace(/\s{2}.*$/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();
if (words.length > 1) 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",
"PETER JOHN PARKER",
"Jr. Peter Parker",
"Jr Peter Parker",
"Sr. Peter Parer",
"Sr Peter Parker",
"Juan Carlos Tenaz LOPEZ I",
"Juan Carlos Tenaz LOPEZ MMM EXAMPLE",
"Juan Carlos Tenaz LOPEZ I of Spain",
"Juan Carlos Tenaz LOPEZ II of Spain",
"Juan Carlos Tenaz LOPEZ III of Spain",
"Juan Carlos Tenaz LOPEZ IV of Spain",
"Juan Carlos Tenaz LOPEZ V of Spain",
"Juan Carlos Tenaz LOPEZ VI of Spain",
"Juan Carlos Tenaz LOPEZ IX of Spain",
"Juan Carlos Tenaz LOPEZ X of Spain",
"Juan Carlos Tenaz LOPEZ XVI of Spain",
"Juan Carlos Tenaz LOPEZ XXX of Spain",
"Juan Carlos Tenaz LOPEZ XL of Spain",
"Juan Carlos Tenaz LOPEZ CLX of Spain",
"Juan Carlos Tenaz LOPEZ CD of Spain",
"Juan Carlos Tenaz LOPEZ CM of Spain",
"Juan Carlos Tenaz LOPEZ MMMCDXVIII of Spain",
];
for (const name of names) {
console.log(getUserInitials(name));
}