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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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];
});
}