5

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".

Community
  • 1
  • 1
BearCode
  • 2,734
  • 6
  • 34
  • 37

2 Answers2

23

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"
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • 2
    Sorry I just noticed it doesn't work for names containing dash ("-"), like for example "luise meyer-schützmeister". It will transform it into "Luise Meyer-schützmeister". Any chance you can improve it? – BearCode Aug 08 '13 at 04:15
  • 7
    To support dashes and single quotes, change /[^\s]+/g to /[^-'\s]+/g – Sebastian Brand Sep 03 '13 at 13:41
-1

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.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • Thanks. Anyways I need a Title Case function (a better version of toTitleCase() from the link above) that works with non-ASCII too. The Title Case function is a combination of uppercase and entire word matching functions. – BearCode Mar 01 '13 at 04:16