dracoblue.net

Encode/Decode special xml characters in Javascript

When you want to convert htmlspecialchars in javascript to not so dangerous text and decode those html entities back again, you may have some convenient methods on a dom entity (like mootools .get('html') and .get('text')).

If you want to do that simple work on simple strings, I use the following functions:

var xml_special_to_escaped_one_map = {
    '&': '&',
    '"': '"',
    '<': '&lt;',
    '>': '&gt;'
};

var escaped_one_to_xml_special_map = {
    '&amp;': '&',
    '&quot;': '"',
    '&lt;': '<',
    '&gt;': '>'
};

function encodeXml(string) {
    return string.replace(/([\&"<>])/g, function(str, item) {
        return xml_special_to_escaped_one_map[item];
    });
};

function decodeXml(string) {
    return string.replace(/(&quot;|&lt;|&gt;|&amp;)/g,
        function(str, item) {
            return escaped_one_to_xml_special_map[item];
    });
}
In javascript, mootools by
@ 23 Dec 2009, Comments at Reddit & Hackernews

Give something back

Were my blog posts useful to you? If you want to give back, support one of these charities, too!

Report hate in social media Campact e.V. With our technology and your help, we protect the oceans from plastic waste. Gesellschaft fur Freiheitsrechte e. V. The civil eye in the mediterranean

Recent Dev-Articles

Read recently

Recent Files

About