D5145c421cd25af6fa577c15219add90

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.

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 !

D5145c421cd25af6fa577c15219add90

Nathan

March 31, 2010, March 31, 2010 13:59, permalink

No rating. Login to rate!

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());
Ddd751c7719f645b592597fc3fbefd9f

Mah

July 3, 2010, July 03, 2010 19:22, permalink

No rating. Login to rate!

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());

Your refactoring





Format Copy from initial code

or Cancel