siberia-man
01-02-2011, 06:25 PM
Last year my colleague asked me help to implement an insertion of html-entities (http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references). This task was interesting but the searching was attractive because there are many copies of the manual parsing of the datum list of entities - phpjs.org :: html_entity_decode (http://phpjs.org/functions/html_entity_decode:424). It is bombastic code, in our opinion is unreasonable - we was looking for the compact and easy code using internal features of browsers. We found the solution completely satisfying our requests - it is compact, easy and uses internal parsing algorithms of browsers.
text in Russian - http://with-love-from-siberia.blogspot.com/2010/12/javascript-html-entities.html
source code - http://code.google.com/p/jsxt/source/browse/trunk/js/web/Entity.js
var Entity = {
encode: function(value)
{
var div = document.createElement('div');
var text = document.createTextNode(value);
div.appendChild(text);
return div.innerHTML.replace(/"/g, '"').replace(/'/g, ''');
},
decode: function(value)
{
var textarea = document.createElement('textarea');
textarea.innerHTML = value;
return textarea.value;
}
};
var original = '& is <ampersand>';
var encoded = Entity.encode(original);
var decoded = Entity.decode(encoded);
alert([original, encoded, decoded].join('\n'));
// will output
// & is <ampersand>
// & is <ampersand>
// & is <ampersand>
text in Russian - http://with-love-from-siberia.blogspot.com/2010/12/javascript-html-entities.html
source code - http://code.google.com/p/jsxt/source/browse/trunk/js/web/Entity.js
var Entity = {
encode: function(value)
{
var div = document.createElement('div');
var text = document.createTextNode(value);
div.appendChild(text);
return div.innerHTML.replace(/"/g, '"').replace(/'/g, ''');
},
decode: function(value)
{
var textarea = document.createElement('textarea');
textarea.innerHTML = value;
return textarea.value;
}
};
var original = '& is <ampersand>';
var encoded = Entity.encode(original);
var decoded = Entity.decode(encoded);
alert([original, encoded, decoded].join('\n'));
// will output
// & is <ampersand>
// & is <ampersand>
// & is <ampersand>