我有一些与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/

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


当前回答

要在JavaScript中解转义HTML实体*,你可以使用小型库HTML -escaper: npm install HTML -escaper

import {unescape} from 'html-escaper';

unescape('escaped string');

或从Lodash或下划线unescape函数,如果你正在使用它。


*)请注意,这些函数并不涵盖所有HTML实体,而只是最常见的,即&,<,>,',"。要解除所有HTML实体的转义,您可以使用库。

其他回答

要在JavaScript中解转义HTML实体*,你可以使用小型库HTML -escaper: npm install HTML -escaper

import {unescape} from 'html-escaper';

unescape('escaped string');

或从Lodash或下划线unescape函数,如果你正在使用它。


*)请注意,这些函数并不涵盖所有HTML实体,而只是最常见的,即&,<,>,',"。要解除所有HTML实体的转义,您可以使用库。

函数decodeHTMLContent(htmlText) { var txt = document.createElement("span"); 三种。innerHTML = htmlText; 返回txt.innerText; } var result = decodeHTMLContent('One &两个,三个“); console.log(结果);

首先创建一个<span id="decodeIt" style="display:none;></span>在身体某处

接下来,将要解码为innerHTML的字符串赋值如下:

document.getElementById("decodeIt").innerHTML=stringtodecode

最后,

stringtodecode=document.getElementById("decodeIt").innerText

下面是整个代码:

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

不客气只是一个信使……全部归功于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

元素。innerText也可以做到这一点。