1

I have a HTML source field and a markup text field. What HTML I write and submit according to that the markup field changes. When I reopen the html field area it just gives the HTML source code of that markup field. Now the issue is, for every thing else except some escaped characters it is giving the correct html. But for escaped characters it is not working properly. e.g.: for a white space source field is returning <p>&nbsp</p>

But for copyright © sign, instead of returning <p> &copy; </p> , it is returning <p>©</p>

So is there any in-built function in JS that returns the HTML part for escaped characters from a string?

I even tried this:

function multiLineHtmlEncode(value) {
    var lines = value.split(/\r\n|\r|\n/);
    for (var i = 0; i < lines.length; i++) {
        lines[i] = htmlEncode(lines[i]);
    }
    return lines.join('\r\n');
}

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

but not working.

MattJ
  • 7,924
  • 1
  • 28
  • 33
koushik
  • 99
  • 1
  • 9

2 Answers2

0

Not sure I totally understand what you're saying, but try this to use the htmlEncode function as defined like this:

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

From HTML-encoding lost when attribute read from input field

Community
  • 1
  • 1
pfrank
  • 2,090
  • 1
  • 19
  • 26
0

If I understand you correctly, try calling htmlEncode() twice on the data:

htmlEncode("©") will produce &copy;, which the browser will render as ©.

But htmlEncode(htmlEncode("©")) will return &amp;copy; which the browser will render as literally &copy;, giving you the actual HTML source, suitably escaped for display.

MattJ
  • 7,924
  • 1
  • 28
  • 33