Issue
I have a function which Capitalize the sentences. But its not able to Capitalize names such as,
D'agostino, Fred
D'agostino, Ralph B.
D'allonnes, C. Revault
D'amanda, Christopher
I am expecting:
D'Agostino, Fred
D'Agostino, Ralph B.
D'Allonnes, C. Revault
D'Amanda, Christopher
Function:
getCapitalized(str){
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) {
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
(title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
}
Can anybody help me figuring out the issue? I have tried using (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'")
but it doesn’t help.
Solution
I’m not sure about all the use-cases you need to take care of, but for the question you asked, you can use regex that looks for word boundaries:
function capitalizeName(name) {
return name.replace(/\b(\w)/g, s => s.toUpperCase());
}
console.log(capitalizeName(`D'agostino, Fred`));
console.log(capitalizeName(`D'agostino, Ralph B.`));
console.log(capitalizeName(`D'allonnes, C. Revault`));
console.log(capitalizeName(`D'amanda, Christopher`));
Answered By – KevBot
Answer Checked By – Robin (BugsFixing Admin)