在JavaScript中表达UTF-16 unicode字符

时间:2011-08-19 19:22:23

标签: javascript unicode

例如,为了表达JavaScript中的字符U + 10400,我使用"\uD801\uDC00"String.fromCharCode(0xD801) + String.fromCharCode(0xDC00)。我如何计算出给定的unicode角色?我想要以下内容:

var char = getUnicodeCharacter(0x10400);

如何从0xD801找到0xDC000x10400

2 个答案:

答案 0 :(得分:17)

根据Henning Makholm提供的wikipedia article,以下函数将返回代码点的正确字符:

function getUnicodeCharacter(cp) {

    if (cp >= 0 && cp <= 0xD7FF || cp >= 0xE000 && cp <= 0xFFFF) {
        return String.fromCharCode(cp);
    } else if (cp >= 0x10000 && cp <= 0x10FFFF) {

        // we substract 0x10000 from cp to get a 20-bits number
        // in the range 0..0xFFFF
        cp -= 0x10000;

        // we add 0xD800 to the number formed by the first 10 bits
        // to give the first byte
        var first = ((0xffc00 & cp) >> 10) + 0xD800

        // we add 0xDC00 to the number formed by the low 10 bits
        // to give the second byte
        var second = (0x3ff & cp) + 0xDC00;

        return String.fromCharCode(first) + String.fromCharCode(second);
    }
}

答案 1 :(得分:4)

  

如何从0xD801找到0xDC000x10400

JavaScript uses UCS-2 internally.这就是String#charCodeAt()无法按照您希望的方式运作的原因。

如果要获取字符串中每个Unicode字符(包括非BMP字符)的代码点,可以使用Punycode.js的实用程序函数在UCS-2字符串和UTF-16代码之间进行转换分:

// String#charCodeAt() replacement that only considers full Unicode characters
punycode.ucs2.decode(''); // [119558]
punycode.ucs2.decode('abc'); // [97, 98, 99]

如果您不需要以编程方式执行此操作,并且您已经拥有该角色,请使用mothereff.in/js-escapes。它会告诉你how to escape any character in JavaScript