可以通过Javascript将十六进制html系统地转换为unicode吗?

Mar*_*ark 1 javascript regex unicode hex

我有以下字符串例如:

"嗨,我正在测试一个奇怪的角色Ů,它是一个带圆圈的U"

现在我的字符串使用html代码Ů显示U-circle.我需要这个是unicode格式,即.\u016E.是否有任何好的系统方法用普通的jilla javascript做到这一点?

nwe*_*hof 9

如果要将数字HTML字符引用转换为Unicode转义序列,请尝试以下方法(不适用于0xFFFF以上的代码点):

function convertCharRefs(string) {
    return string
        .replace(/&#(\d+);/g, function(match, num) {
            var hex = parseInt(num).toString(16);
            while (hex.length < 4) hex = '0' + hex;
            return "\\u" + hex;
        })
        .replace(/&#x([A-Za-z0-9]+);/g, function(match, hex) {
            while (hex.length < 4) hex = '0' + hex;
            return "\\u" + hex;
        });
}
Run Code Online (Sandbox Code Playgroud)

如果您只想解码字符引用:

function decodeCharRefs(string) {
    return string
        .replace(/&#(\d+);/g, function(match, num) {
            return String.fromCharCode(num);
        })
        .replace(/&#x([A-Za-z0-9]+);/g, function(match, num) {
            return String.fromCharCode(parseInt(num, 16));
        });
}
Run Code Online (Sandbox Code Playgroud)

这两个函数都使用String.replace函数作为替换.