在JavaScript中表达UTF-16 unicode字符

gil*_*ly3 15 javascript unicode

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

var char = getUnicodeCharacter(0x10400);
Run Code Online (Sandbox Code Playgroud)

我如何找到0xD8010xDC00来自0x10400

Arn*_*anc 17

根据Henning Makholm提供的维基百科文章,以下函数将返回代码点的正确字符:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我知道:)函数有目的地返回那些代码点的javascript文字(所以,``\ uD801\uDC00``为`0x10400`).我修改了函数来代替返回字符. (2认同)

Mat*_*ens 5

我如何查找0xD8010xDC00来自0x10400

JavaScript在内部使用UCS-2。这就是为什么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]
Run Code Online (Sandbox Code Playgroud)

如果您不需要以编程方式进行操作,并且已经有了角色,则只需使用mothereff.in/js-escapes即可。它将告诉您如何转义JavaScript中的任何字符