Title Case in JavaScript for diacritics (non-ASCII)

不打扰是莪最后的温柔 提交于 2019-12-22 00:29:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!