【问题标题】:HTML Entity to Unicode conversion [duplicate]HTML实体到Unicode转换[重复]
【发布时间】:2014-02-04 08:31:16
【问题描述】:

有没有办法将 HTML 实体转换为 Javascript 中的 unicode 字符?

我试过了

var unicodeHtmlEntity = function (t) {
    numericValue = parseInt(t.slice(2, -1), 10);
    numericValue = numericValue.toString(16);
    return "\\u" + numericValue;
};

函数可以像€ 一样调用,但返回字符串\u20ac,而不是 € 的 unicode 字符。有什么想法吗?

【问题讨论】:

标签: javascript unicode html-entities


【解决方案1】:

这应该适用于绝大多数情况:

function unicodeHtmlEntity (t) {
    var numericValue = parseInt(t.slice(2, -1), 10);
    return String.fromCharCode(numericValue);
}

如果您确实需要支持“星体”位面中的角色,可以使用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint#Getting_it_to_work_with_higher_values 代替 String.fromCharCode()。

我想您知道您的代码不处理十六进制实体,只处理十进制实体。为了支持这些,您可以执行以下操作:

function unicodeHtmlEntity (t) {
    var hex = t.charAt(2) === 'x';
    var base = hex ? 16 : 10;
    var pos = hex ? 3 : 2;
    var numericValue = parseInt(t.slice(pos, -1), base);
    return String.fromCharCode(numericValue);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-17
    • 2010-09-08
    • 1970-01-01
    • 2015-07-15
    • 2015-06-11
    相关资源
    最近更新 更多