CNKR
CNKR

Reputation: 578

Replacing script tag with cdata tags

I want to replace <script with <![CDATA[<script , </script> with </script>]]> and put this into a new dom element.

So i wrote a regular expression to that replace the tags and i need to put this script as inner html to an element like as below

I wrote below code

  var html = "<script src=\"https://dynamic.test.com/test/test/common/js/test.js\"></script>";
  html = html.replace(/<script/ig,"<!CDATA[<script")
             .replace(/<\/script>/ig,"</script>]]>");


 console.log(""$j("<test/>").html(html)[0].outerHTML);

I am getting output as below

 <test><!--CDATA[<script src="https://dynamic.test.com/test/test/common/js/test.js"-->]]&gt;</test>

But the expected output is

    <test><!--CDATA[<script src="https://dynamic.test.com/test/test/common/js/test.js"></script>]]></test>  

Upvotes: 0

Views: 504

Answers (1)

Quentin
Quentin

Reputation: 943556

It looks like your document is in HTML mode (i.e. served as text/html). HTML does not support explicit CDATA sections. You would need an XML document.

Use entities instead. Replace <, >, et al with &lt;, &gt; etc.

Better yet: Stop munging strings to create HTML. Use appendChild and createTextNode.

Upvotes: 1

Related Questions