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 powered by Disqus

Recent Files

Advertisement

Recent Dev-Articles

Read recently

About

Blogroll