The solution I found, which works for most language accents latinas and germanic, was with regex:
string.replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word){
return separator + word.charAt(0).toUpperCase() + word.slice(1);
});
In the regex I try to find one character not on this list [A-zÀ-ú]
(optional, hence the ?
) and a word of one or more letters with [A-zÀ-ú]+
, both with capture group to work within the replace function.
Example:
String.prototype.capitalize = function(){
return String(this).replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word){
return separator + word.charAt(0).toUpperCase() + word.slice(1);
});
}
alert('a anna-karin gosta de música!'.capitalize());
Good suggestion, but fails in names like "Anna-Karin" or "O'Leary". For example the phrase
"a anna-karin e o o'leary estão contentes"
gives"A Anna-karin E O O'leary Estão Contentes"
.– Sergio
Because it is a JS version of a language function they had to respect the output format of the original function. And, perhaps because technically "Anna-Karin" and "O'Leary" are a single word, this is what ucwords() from PHP returns.
– Bruno Augusto