How to remove `//<![CDATA[` and end `//]]>` with javascript from string?
Asked Answered
R

5

11

How to remove //<![CDATA[ and end //]]> with javascript from string?

var title = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>" ;

needs to become

var title = "A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks";

How to do that?

Refrigerant answered 7/6, 2012 at 15:20 Comment(0)
M
27

You can use the String.prototype.replace method, like:

title = title.replace("<![CDATA[", "").replace("]]>", "");

This will replace each target substring with nothing. Note that this will only replace the first occurrence of each, and would require a regular expression if you want to remove all matches.

Reference:

Margartmargate answered 7/6, 2012 at 15:22 Comment(2)
How will it work if your string has multiple <![CDATA[ ?Uprise
This trivial answer is wrong, because you can encode the literal string "<![CDATA[" inside a <![CDATA[ structure itself - the only way to properly "remove" the outside <![CDATA[ string is to remove the wrappers one-at-a-time from left to right, taking care NOT to remove any encoded "<![CDATA[" constructs that are meant to be inside there... Specifically - the thing you want to DECODE originally had THIS done to it in order to first ENCODE it: .replaceAll(']]>',']]]]><![CDATA[>');Kirkkirkcaldy
W
1

You ought to be able to do this with a regex. Maybe something like this?:

var myString = "<![CDATA[A Survey of Applications of Identity-Based Cryptography in Mobile Ad-Hoc Networks]]>";
var myRegexp = /<!\[CDATA\[(.*)]]>/;
var match = myRegexp.exec(myString);
alert(match[1]);
Womanhater answered 7/6, 2012 at 15:26 Comment(1)
I would just get the array value in a single line: var match = myRegexp.exec(myString)[1];Galba
M
1

I suggest this wider way to remove leading and trailing CDATA stuff :

title.trim().replace(/^(\/\/\s*)?<!\[CDATA\[|(\/\/\s*)?\]\]>$/g, '')

It will also work if CDATA header and footer are commented.

Micronucleus answered 15/10, 2019 at 15:0 Comment(0)
S
1

The regular expresion /^(<!\[CDATA\[)|(]]>)$/gm worked for me without looping.

Spermatium answered 9/12, 2021 at 17:35 Comment(0)
K
0

You must perform the OPPOSITE of what was originally done to the string to ENCODE it, which was this:-

mystr='<!CDATA[' + mystr.replaceAll(']]>',']]]]><![CDATA[>') + ']]>'

All the other answers on this page that suggest "replace" without using a loop are wrong.

Kirkkirkcaldy answered 30/8, 2021 at 6:48 Comment(1)
FYI: CDATA encoding requires that replaceAll step to "escape" any potential "]]>" sequence that might be inside the string you want to encode.Kirkkirkcaldy

© 2022 - 2024 — McMap. All rights reserved.