使用 javascript 将 HTML 字符实体转换回常规文本

IT技术 javascript character-entities
2021-03-07 11:08:48

问题说明了一切:)

例如。我们有>,我们>需要使用 javascript

更新:似乎 jquery 是最简单的方法。但是,有一个轻量级的解决方案会很好。更像是一个能够自行完成此操作的函数。

5个回答

你可以这样做:

String.prototype.decodeHTML = function() {
    var map = {"gt":">" /* , … */};
    return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
        if ($1[0] === "#") {
            return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16)  : parseInt($1.substr(1), 10));
        } else {
            return map.hasOwnProperty($1) ? map[$1] : $0;
        }
    });
};
@nuaavee:因为字符引用可以是十进制或十六进制表示法: =  
2021-04-28 11:08:48
整洁的解决方案。不过我有一个问题——你为什么要检查第 5 行的十六进制字符代码?
2021-05-10 11:08:48
任何人都可以分享扩展的地图变量吗?
2021-05-12 11:08:48
这个浏览器依赖吗?我的意思是十六进制符号只适用于某些浏览器吗?
2021-05-14 11:08:48
@nuaavee:不,那是基本的 SGML/HTML
2021-05-14 11:08:48
function decodeEntities(s){
    var str, temp= document.createElement('p');
    temp.innerHTML= s;
    str= temp.textContent || temp.innerText;
    temp=null;
    return str;
}

alert(decodeEntities('<'))

/*  returned value: (String)
<
*/
这在不受信任的(用户输入的)文本上使用是不安全的。请参阅此评论stackoverflow.com/questions/1147359/...
2021-05-18 11:08:48

这是一个用于解码整个 HTML 文档的“类”。

HTMLDecoder = {
    tempElement: document.createElement('span'),
    decode: function(html) {
        var _self = this;
        html.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,
            function(str) {
                _self.tempElement.innerHTML= str;
                str = _self.tempElement.textContent || _self.tempElement.innerText;
                return str;
            }
        );
    }
}

请注意,我使用 Gumbo 的正则表达式来捕获实体,但对于完全有效的 HTML 文档(或 XHTML),您可以简单地使用/&[^;]+;/g.

我知道那里有一些库,但这里有一些针对浏览器的解决方案。当将 html 实体数据字符串放入您希望显示字符的人类可编辑区域(例如 textarea 或 input[type=text])时,这些效果很好。

我添加这个答案是因为我必须支持旧版本的 IE,我觉得它结束了几天的研究和测试。我希望有人觉得这很有用。

首先,这是针对使用 jQuery 的更现代的浏览器,请注意,如果您必须支持 10(7、8 或 9)之前的 IE 版本,则不应使用它,因为它会去掉换行符,只留下一个长行的文本。

if (!String.prototype.HTMLDecode) {
    String.prototype.HTMLDecode = function () {
            var str = this.toString(),
            $decoderEl = $('<textarea />');

        str = $decoderEl.html(str)
            .text()
            .replace(/<br((\/)|( \/))?>/gi, "\r\n");

        $decoderEl.remove();

        return str;
    };
}

下一个基于 kennebec 的上述工作,其中有一些差异主要是为了旧的 IE 版本。这不需要 jQuery,但仍然需要浏览器。

if (!String.prototype.HTMLDecode) {
    String.prototype.HTMLDecode = function () {
        var str = this.toString(),
            //Create an element for decoding            
            decoderEl = document.createElement('p');

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if (str.length == 0) {
            return str;
        }

        //convert newlines to <br's> to save them
        str = str.replace(/((\r\n)|(\r)|(\n))/gi, " <br/>");            

        decoderEl.innerHTML = str;
        /*
        We use innerText first as IE strips newlines out with textContent.
        There is said to be a performance hit for this, but sometimes
        correctness of data (keeping newlines) must take precedence.
        */
        str = decoderEl.innerText || decoderEl.textContent;

        //clean up the decoding element
        decoderEl = null;

        //replace back in the newlines
        return str.replace(/<br((\/)|( \/))?>/gi, "\r\n");
    };
}

/* 
Usage: 
    var str = "&gt;";
    return str.HTMLDecode();

returned value: 
    (String) >    
*/

没有内置任何东西,但是已经编写了许多库来执行此操作。

是一个。

在这里,一个是jQuery插件。