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

妖精的绣舞 提交于 2019-12-19 17:16:31

问题


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?


回答1:


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:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace



回答2:


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]);



回答3:


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.



来源:https://stackoverflow.com/questions/10934789/how-to-remove-cdata-and-end-with-javascript-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!