Insert Unicode character into JavaScript

后端 未结 4 2159
抹茶落季
抹茶落季 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:31

    Although @ruakh gave a good answer, I will add some alternatives for completeness:

    You could in fact use even var Omega = 'Ω' in JavaScript, but only if your JavaScript code is:

    • inside an event attribute, as in onclick="var Omega = 'Ω'; alert(Omega)" or
    • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

    In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like Ω are recognized. The restrictions make this an impractical approach in most cases.

    You can also enter the Ω character as such, as in var Omega = 'Ω', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

    Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

    You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

提交回复
热议问题