Unescape HTML entities in Javascript?

前端 未结 30 2932
野趣味
野趣味 2020-11-21 05:40

I have some Javascript code that communicates with an XML-RPC backend. The XML-RPC returns strings of the form:


30条回答
  •  情深已故
    2020-11-21 05:51

    The trick is to use the power of the browser to decode the special HTML characters, but not allow the browser to execute the results as if it was actual html... This function uses a regex to identify and replace encoded HTML characters, one character at a time.

    function unescapeHtml(html) {
        var el = document.createElement('div');
        return html.replace(/\&[#0-9a-z]+;/gi, function (enc) {
            el.innerHTML = enc;
            return el.innerText
        });
    }
    

提交回复
热议问题