我有一些与XML-RPC后端通信的JavaScript代码。 XML-RPC返回如下形式的字符串:

<img src='myimage.jpg'>

然而,当我使用JavaScript将字符串插入到HTML中时,它们会逐字呈现。我看到的不是图像,而是字符串:

<img src='myimage.jpg'>

我猜想HTML是通过XML-RPC通道转义的。

如何在JavaScript中解除字符串转义?我尝试了这个页面上的技巧,但没有成功:http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/

诊断这个问题的其他方法是什么?


当前回答

我尝试从JSON数组中删除&。上面的例子都不是,但是https://stackoverflow.com/users/2030321/chris提供了一个很好的解决方案,让我解决了我的问题。

var stringtodecode="<B>Hello</B> world<br>";
document.getElementById("decodeIt").innerHTML=stringtodecode;
stringtodecode=document.getElementById("decodeIt").innerText

我没有使用,因为我不知道如何将它插入一个模态窗口,将JSON数据拉到一个数组中,但我确实尝试了基于示例的这一点,并且它工作:

var modal = document.getElementById('demodal');
$('#ampersandcontent').text(replaceAll(data[0],"&amp;", "&"));

我喜欢它,因为它简单,而且有效,但不确定为什么它没有被广泛使用。搜索hi & low找到一个简单的解决方案。 我继续寻求对语法的理解,以及使用它是否有任何风险。还什么都没找到。

其他回答

这个问题没有指定x的来源,但如果可以的话,它有意义,可以防御恶意(或来自我们自己的应用程序的意外)输入。例如,假设x的值为&< >脚本alert('你好');> < /脚本。在jQuery中处理这个问题的一个安全而简单的方法是:

var x    = "&amp; <script>alert('hello');</script>";
var safe = $('<div />').html(x).text();

// => "& alert('hello');"

可以通过https://gist.github.com/jmblog/3222899找到。我想不出有什么理由不使用这个解决方案,因为它至少和其他解决方案一样短(如果不是更短的话),并且提供了对XSS的防御。

(我最初是作为评论发布这篇文章的,但由于同一线程中的后续评论要求我这样做,所以我将其作为回答添加进来)。

对于只说一句话的男人:

const htmlDecode = innerHTML => Object.assign(document.createElement('textarea'), {innerHTML}).value;

console.log(htmlDecode('Complicated - Dimitri Vegas &amp; Like Mike'));
var htmlEnDeCode = (function() {
    var charToEntityRegex,
        entityToCharRegex,
        charToEntity,
        entityToChar;

    function resetCharacterEntities() {
        charToEntity = {};
        entityToChar = {};
        // add the default set
        addCharacterEntities({
            '&amp;'     :   '&',
            '&gt;'      :   '>',
            '&lt;'      :   '<',
            '&quot;'    :   '"',
            '&#39;'     :   "'"
        });
    }

    function addCharacterEntities(newEntities) {
        var charKeys = [],
            entityKeys = [],
            key, echar;
        for (key in newEntities) {
            echar = newEntities[key];
            entityToChar[key] = echar;
            charToEntity[echar] = key;
            charKeys.push(echar);
            entityKeys.push(key);
        }
        charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
        entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
    }

    function htmlEncode(value){
        var htmlEncodeReplaceFn = function(match, capture) {
            return charToEntity[capture];
        };

        return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
    }

    function htmlDecode(value) {
        var htmlDecodeReplaceFn = function(match, capture) {
            return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
        };

        return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
    }

    resetCharacterEntities();

    return {
        htmlEncode: htmlEncode,
        htmlDecode: htmlDecode
    };
})();

这是ExtJS的源代码。

不客气只是一个信使……全部归功于ourcodeworld.com,链接如下。

window.htmlentities = {
        /**
         * Converts a string to its html characters completely.
         *
         * @param {String} str String with unescaped HTML characters
         **/
        encode : function(str) {
            var buf = [];

            for (var i=str.length-1;i>=0;i--) {
                buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
            }

            return buf.join('');
        },
        /**
         * Converts an html characterSet into its original character.
         *
         * @param {String} str htmlSet entities
         **/
        decode : function(str) {
            return str.replace(/&#(\d+);/g, function(match, dec) {
                return String.fromCharCode(dec);
            });
        }
    };

出处:https://ourcodeworld.com/articles/read/188/encode-and-decode-html-entities-using-pure-javascript

如果你正在使用jQuery:

function htmlDecode(value){ 
  return $('<div/>').html(value).text(); 
}

否则,使用Strictly Software的Encoder对象,它有一个很棒的htmlDecode()函数。