Search This Blog

Monday, May 22, 2017

Javascript: How to encode and decode HTML using javascript?

Using below jquery code you can encode HTML

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

htmlEncode('<b>test</b>')
// result"&lt;b&gt;test&lt;/b&gt;"

No comments:

Post a Comment