12
4

3 回答 3

22

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.

于 2010-09-30T22:41:36.517 回答
10

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

于 2013-06-30T21:52:31.427 回答
3

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...

于 2010-09-30T23:24:12.273 回答