5

请查看在(理论上可能的)字符串上运行的此脚本:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery.js"></script>
<script>
    $(function () {
        $("#click").click(function () {
            var txt = $('#high-unicode').text();
            var codes = '';
            for (var i = 0; i < txt.length; i++) {
                if (i > 0) codes += ',';
                codes += txt.charCodeAt(i);
            }
            alert(codes);
        });
    });
</script>
</head>
<body>
<span id="click">click</span><br />
<span id="high-unicode">&#x1D465;<!-- mathematical italic small x -->&#xF31E0;<!-- some char from Supplementary Private Use Area-A -->A<!-- char A -->&#x108171;<!-- some char from Supplementary Private Use Area-B --></span>
</body>
</html>

代替“55349,56421,56204,56800,65,56288,56689”,是否有可能得到“119909,995808,65,1081713”?我已经阅读了 more-utf-32-aware-javascript-stringQ:从 UTF-16 转换为字符代码的算法是什么?+问:没有更简单的方法吗?来自unicode.org/faq/utf_bom,但我不确定如何使用此信息。

4

1 回答 1

6

看起来您必须手动解码代理对。例如:

function decodeUnicode(str) {
    var r = [], i = 0;
    while(i < str.length) {
        var chr = str.charCodeAt(i++);
        if(chr >= 0xD800 && chr <= 0xDBFF) {
            // surrogate pair
            var low = str.charCodeAt(i++);
            r.push(0x10000 + ((chr - 0xD800) << 10) | (low - 0xDC00));
        } else {
            // ordinary character
            r.push(chr);
        }
    }
    return r;
}

完整代码:http: //jsfiddle.net/twQWU/

于 2013-02-04T05:58:09.350 回答