3

I'm currently doing a big switch statement in my javascript to convert

            case 176: char = '\u00B0'; break;
            case 177: char = '\u00B1'; break;
            case 178: char = '\u00B2'; break;
            case 179: char = '\u00B3'; break;
            case 180: char = '\u00B4'; break;
Justin808
  • 20,859
  • 46
  • 160
  • 265

3 Answers3

8

if your variable is named intVar you could use ...

var stringVar = String.fromCharCode(intVar);

... to get the unicode character.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 2
    `String.fromCharCode(intVar)` won’t work for supplementary Unicode characters. If `intVar` is `119558` (`0x1D306`, for the `''` character), for example. See [my answer](http://stackoverflow.com/a/9109467/96656) for a solution that works for any code point. – Mathias Bynens Feb 02 '12 at 08:57
  • 1
    I want to convert hexadecimal number like var i = 0x1F64F; To its equivalent emosy symbol see http://apps.timwhitlock.info/unicode/inspect/hex/1F64F – Vivacity InfoTech Oct 17 '14 at 06:23
4

JavaScript uses UCS-2 internally.

Thus, String.fromCharCode(intVar) won’t work for supplementary Unicode characters. If intVar is 119558 (0x1D306, for the '' character), for example.

If you want to create a string based on a non-BMP Unicode code point, you could use Punycode.js’s utility functions to convert between UCS-2 strings and UTF-16 code points:

// `String.fromCharCode` replacement that doesn’t make you enter the surrogate halves separately
punycode.ucs2.encode([0x1d306]); // ''
punycode.ucs2.encode([119558]); // ''
punycode.ucs2.encode([97, 98, 99]); // 'abc'
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
2

You can use String.fromCharCode(i). Note that arguments are expected to be UTF-16 encoded values. See ECMA-262 chapter 15.5.3.2 for details.

McDowell
  • 107,573
  • 31
  • 204
  • 267