javascript 如何使用javascript从字符串中删除`//<![CDATA[`并结束`//]]>`?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10934789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:32:06  来源:igfitidea点击:

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

javascriptjqueryregexcdata

提问by Alireza

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

如何从字符串中删除//<![CDATA[//]]>以javascript结尾?

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?

怎么做?

回答by Ian

You can use the String.prototype.replacemethod, like:

您可以使用该String.prototype.replace方法,例如:

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:

参考:

回答by Curtis

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

回答by Vince

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

我建议使用这种更广泛的方法来删除前导和尾随 CDATA 内容:

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

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

如果 CDATA 页眉和页脚被注释,它也将起作用。