Radu Dascălu Radu Dascălu - 5 months ago 9
HTML Question

Revert a jQuery function, from xml to html and back

I have to worked with xml files in jQuery, and jQuery can't work with

<
,
>
,
&
and other codes. I found this code on google:

function escapeHtml(text) {
var map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
};
return text.replace(/[&<>]/g, function(m) {
return map[m];
});
}


It works, but now I need to export this file, and it returns with
&lt;
&gt;
as text, is there a way to revert this back?

Answer

You can just do it like this by swapping the keys and objects and using Object.keys

function toHTML(text) {
    var map = {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
    };
    return text.replace(new RegExp(Object.keys(map).join("|"),"g"), function(m) {
        return map[m];
    });
}