I have a form that when the user enters their name it automatically capitalise’s the first character of each, but when the user has a special character within their name such as ‘è’ then the code then precedes to capitalise the next character after.
EG:
Joesph Bloggs works fine but if I enter Joèsph Bloggs it actually outputs it as JoèSph Bloggs.
Notice the capital S in the middle of the name. The code I use at present is the following, any ideas how to prevent this?
Thanks
capFirstLetters= function(str){
return str.toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();});
}
It’s because JS regexes aren’t unicode aware, sadly. A slightly better way of doing it would probably be:
This version of the regex would match a whitespace character or the start of the string, followed by a non-whitespace character.
Note also that I have no idea what the behaviour here will be if people use non-extended-latin names, like those involving Chinese or Japanese characters. It is also unlikely to work correctly for languages which are read right-to-left (eg. Hebrew).
This kind of thing is hard to get right and it may make more sense to use two separate fields for first and last name — or to simply leave user input the way it is.