Search code examples
jqueryhtmlxmlrevert

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?


Solution

  • 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];
        });
    }