Javascript literals for characters higher than U+FFFF

安稳与你 提交于 2021-02-10 23:32:09

问题


My javsacript source code is strictly ascii and I want to represent the anger symbol in a string literal. Is that possible in javascript?


回答1:


JavaScript strings are effectively UTF-16, so you can write the surrogate pair using Unicode escapes: "\uD83D\uDCA2" (this is what's shown on that page for the Java source code, which also works in JavaScript).

As of ES2015 (ES6), you can also write it as \u{1F4A2} rather than working out the surrogate pairs (spec).

Example:

Using \uD83D\uDCA2:

document.body.innerHTML =
  "(Of course, this only works if the font has that character.)" +
  "<br>As \\uD83D\\uDCA2: \uD83D\uDCA2";

Using \u{1F4A2} (if your browser supports the new ES2015 feature):

document.body.innerHTML =
  "(Of course, this only works if the font has that character.)" +
  "<br>As \\u{1F4A2}: \u{1F4A2}";

Here's an example using U+1D44E (\uD835\uDC4E, \u{1D44E}), the stylized a used in mathematics, which shows here on SO for me on Linux (whereas your :anger: emoji doesn't, but does if I use Windows 8.1):

Using \uD835\uDC4E:

document.body.innerHTML =
  "(Of course, this only works if your browser has that symbol.)" +
  "<br>As \\uD835\\uDC4E: \uD835\uDC4E";

Using \u{1D44E} (if your browser supports the new ES2015 feature):

document.body.innerHTML =
  "(Of course, this only works if your browser has that symbol.)" +
  "<br>As \\u{1D44E}: \u{1D44E}";


来源:https://stackoverflow.com/questions/35481592/javascript-literals-for-characters-higher-than-uffff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!