2

I am adding some javascript code to a script tag programmatically by assigning it to InnerHtml property of the HtmlNode

scriptNode.InnerHtml =new_script;

and my javascript contains less than < and/or greater than > characters and that causes problems - distorts my resulting javascript. How can I escape those.

Here is a sample javascript that is causing the problem:

function myFunc(el){
    var i=0
    for (;i < el.choice.length;i++){
        ....
    }
}

How can I escape the < in the code above while assigning the code as InnerHtml for my Html node?

Coding Duchess
  • 6,445
  • 20
  • 113
  • 209
  • 1
    Possible duplicate of [Fastest method to escape HTML tags as HTML entities?](http://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities) – GolezTrol May 12 '16 at 17:28
  • No, that does nto work for me. I am dealing with actual javascript code that gets edited when assigned to innerHtml – Coding Duchess May 12 '16 at 18:41

3 Answers3

2

You can either use HTML codes of > and < which are &lt; and &gt;

OR

You can wrap your script within CDATA like this:

<script>
    <![CDATA[
        --YOUR SCRIPT--
    ]]>
</script>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
2

For that you need to encode and decode the javascript content. please refer the following code :

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;"

As posted previously by @CMS

Community
  • 1
  • 1
Hardipsinh Jadeja
  • 1,180
  • 1
  • 13
  • 30
0

Here is a simple code that escapes a string:

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
Nick Messing
  • 494
  • 5
  • 14