function encodeHTML(html)
{
encoded = encodeURI(html);
encodedChars = encoded.match(/%([ABCDE0-9]+)/g);
for (encodedCharNumber in encodedChars)
{
encodedChar = encodedChars[encodedCharNumber];
htmlEncodedChar = '&#' + parseInt(encodedChar.replace('%',''),16) + ';';
encoded = encoded.replace(encodedChar,htmlEncodedChar);
}
return encoded;
}
Refactorings
No refactoring yet !
Nathan
March 31, 2010, March 31, 2010 13:59, permalink
D'oh, just realised you can do it in one line with JQuery, which I am using in my project.
$('#my-element').text($('#my-element').html());
Mah
July 3, 2010, July 03, 2010 19:22, permalink
if at all you need to store the value in a variable and then store that to a field for the database, here is the code
var textVal = $('<div />').text($(this).contents().find("body").html());
$("#dest_field).val(textVal .html());
All HTML special characters can have their numeric values used instead of their normal symbols. So > can also be represented by >. Javascript's encodeURI() converts characters into these numbers, but uses the HEX versions. I've made a simple function using this idea to escape HTML. I tried doing it using back references, but couldn't get it working.