Unicode value \\uXXXX to Character in Javascript

浪子不回头ぞ 提交于 2019-11-27 08:26:20

The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.

You could ammend your code to make a string (without the '\u') from your hex number, and call

var n = parseInt(hexString, 16);

to get the value. Then you could call .fromCharCode() with that value.

A useful snippet for replacing all unicode-encoded special characters in a text is:

var rawText = unicodeEncodedText.replace(
                  /\\u([0-9a-f]{4})/g, 
                  function (whole, group1) {
                      return String.fromCharCode(parseInt(group1, 16));
                  }
              );

Using replace, fromCharCode and parseInt

If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:

var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
  var hi = i >> 4;
  var lo = i % 16;
  var code = "'\\u00" + hex[hi] + hex[lo] + "'";
  var char = eval(code);
  s += char;
}
document.write(s);

Of course, just using String.fromCharCode(i) would be a lot easier...

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