Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="https://developer.mozilla.org/en/DOM/document.createCDATASection" rel="nofollow"><code>document.createCDATASection</code></a> should do it, but the real answer to your question is that although HTML 5 does have <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#cdata-sections" rel="nofollow">CDATA sections</a> cross-browser support for them is pretty spotty.</p> <p>EDIT</p> <p>The CDATA sections just aren't in the HTML 4 definition, so most browsers won't recognize them.</p> <p>But it doesn't require a full DOM parser. Here's a simple lexical solution that will fix the problem.</p> <pre><code>function htmlWithCDATASectionsToHtmlWithout(html) { var ATTRS = "(?:[^&gt;\"\']|\"[^\"]*\"|\'[^\']*\')*", // names of tags with RCDATA or CDATA content. SCRIPT = "[sS][cC][rR][iI][pP][tT]", STYLE = "[sS][tT][yY][lL][eE]", TEXTAREA = "[tT][eE][xX][tT][aA][rR][eE][aA]", TITLE = "[tT][iI][tT][lL][eE]", XMP = "[xX][mM][pP]", SPECIAL_TAG_NAME = [SCRIPT, STYLE, TEXTAREA, TITLE, XMP].join("|"), ANY = "[\\s\\S]*?", AMP = /&amp;/g, LT = /&lt;/g, GT = /&gt;/g; return html.replace(new RegExp( // Entities and text "[^&lt;]+" + // Comment "|&lt;!--"+ANY+"--&gt;" + // Regular tag "|&lt;\/?(?!"+SPECIAL_TAG_NAME+")[a-zA-Z]"+ATTRS+"&gt;" + // Special tags "|&lt;\/?"+SCRIPT +"\\b"+ATTRS+"&gt;"+ANY+"&lt;\/"+SCRIPT +"\\s*&gt;" + "|&lt;\/?"+STYLE +"\\b"+ATTRS+"&gt;"+ANY+"&lt;\/"+STYLE +"\\s*&gt;" + "|&lt;\/?"+TEXTAREA+"\\b"+ATTRS+"&gt;"+ANY+"&lt;\/"+TEXTAREA+"\\s*&gt;" + "|&lt;\/?"+TITLE +"\\b"+ATTRS+"&gt;"+ANY+"&lt;\/"+TITLE +"\\s*&gt;" + "|&lt;\/?"+XMP +"\\b"+ATTRS+"&gt;"+ANY+"&lt;\/"+XMP +"\\s*&gt;" + // CDATA section. Content in capturing group 1. "|&lt;!\\[CDATA\\[("+ANY+")\\]\\]&gt;" + // A loose less-than "|&lt;", "g"), function (token, cdataContent) { return "string" === typeof cdataContent ? cdataContent.replace(AMP, "&amp;amp;").replace(LT, "&amp;lt;") .replace(GT, "&amp;gt;") : token === "&lt;" ? "&amp;lt;" // Normalize loose less-thans. : token; }); } </code></pre> <p>Given</p> <pre><code>&lt;b&gt;foo&lt;/b&gt;&lt;![CDATA[&lt;i&gt;bar&lt;/i&gt;]]&gt; </code></pre> <p>it produces</p> <pre><code>&lt;b&gt;foo&lt;/b&gt;&amp;lt;i&amp;gt;bar&amp;lt;/i&amp;gt; </code></pre> <p>and given something that looks like a CDATA section inside a <code>script</code> or other special tag or comment, it correctly does not muck with it:</p> <pre><code>&lt;script&gt;/*&lt;![CDATA[*/foo=bar&lt;baz&amp;amp;//]]&gt;&lt;/script&gt;&lt;![CDATA[fish: &lt;&gt;&lt;]]&gt; </code></pre> <p>becomes</p> <pre><code>&lt;script&gt;/*&lt;![CDATA[*/foo=bar&lt;baz&amp;amp;//]]&gt;&lt;/script&gt;fish: &amp;lt;&amp;gt;&amp;lt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload