The solution I found, which works for most accents in Latin and German languages, was with regex:
string.replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word){
return separator + word.charAt(0).toUpperCase() + word.slice(1);
});
In regex I try to find a character not present in this list [A-zÀ-ú]
(optional, hence the ?
) and a word of one or more letters with [A-zÀ-ú]+
, both with capturing group to be able 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());