Insert Unicode character into JavaScript

后端 未结 4 2151
抹茶落季
抹茶落季 2020-11-27 03:09

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 an

4条回答
  •  被撕碎了的回忆
    2020-11-27 03:29

    One option is to put the character literally in your script, e.g.:

    const omega = 'Ω';
    

    This requires that you let the browser know the correct source encoding, see Unicode in JavaScript

    However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint:

    const omega = '\u{3a9}';
    
    // or:
    
    const omega = String.fromCodePoint(0x3a9);
    

    This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:

    • HTML escapes (const omega = 'Ω';): only work when rendered unescaped in an HTML element
    • old style string escapes (const omega = '\u03A9';): restricted to UTF-16
    • String.fromCharCode: restricted to UTF-16

提交回复
热议问题