问题
Is it possible to create a JavaScript function that can convert a string to title case but one that works with non-ASCII (Unicode) characters? For example with characters like:
Áá Àà Ăă Ắắ Ằằ Ẵẵ Ẳẳ Ââ Ấấ Ầầ Ẫẫ Ẩẩ Ǎǎ Åå Ǻǻ Ää Ǟǟ Ãã
Éé Èè Ĕĕ Êê Ếế Ềề Ễễ Ểể Ěě Ëë Ẽẽ Ėė Ȩȩ Ḝḝ Ęę Ēē Ḗḗ Ḕḕ
etc.
For example if the string is "anders ångström", it should transform it into "Anders Ångström". The script that already exists it will transform into "Anders åNgström".
回答1:
Try this:
var str = 'anders ångström';
str = str.replace(/[^\s]+/g, function(word) {
return word.replace(/^./, function(first) {
return first.toUpperCase();
});
});
console.log(str); //=> "Anders Ångström"
回答2:
Javascript's built-in conversion is Unicode-aware, for instance "å".toUpperCase()
returns "Å"
. So I'm not sure what your "existing script" is doing wrong.
If, however, you need full Unicode-aware case conversion (or other Unicode suport), you may want to look at unicode.js.
来源:https://stackoverflow.com/questions/15150168/title-case-in-javascript-for-diacritics-non-ascii