我有以下字符串,例如:
"嗨,我正在测试一个奇怪的字符Ů,它是一个带圆圈的U "
现在我的字符串使用html代码Ů
来显示u形圆。我需要这个,但在unicode格式,即。u016E
。有什么好的系统方法可以用普通的javascript来做到这一点吗?
如果您想将数字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;
});
}
如果你只是想解码字符引用:
function decodeCharRefs(string) {
return string
.replace(/&#(d+);/g, function(match, num) {
return String.fromCodePoint(num);
})
.replace(/&#x([A-Za-z0-9]+);/g, function(match, num) {
return String.fromCodePoint(parseInt(num, 16));
});
}
两个函数都用String.replace
代替一个函数