Search code examples
javascripthtmlunicode

Insert Unicode character into JavaScript


I need to insert an Omega (Ω) onto my html page. I am using its HTML escaped code to do that, so I can write Ω and get Ω. That's all fine and well when I put it into a HTML element; however, when I try to put it into my JS, e.g. var Omega = Ω, it parses that code as JS and the whole thing doesn't work. Anyone know how to go about this?


Solution

  • I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

    var Omega = '\u03A9';
    

    (Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

    Edited to add (in 2022): There now exists an alternative form that better supports codepoints above U+FFFF:

    let Omega = '\u{03A9}';
    let desertIslandEmoji = '\u{1F3DD}';
    

    Judging from https://caniuse.com/mdn-javascript_builtins_string_unicode_code_point_escapes, most or all browsers added support for it in 2015, so it should be reasonably safe to use.