【问题标题】:Clean away CDATA from string从字符串中清除 CDATA
【发布时间】:2014-05-13 14:44:36
【问题描述】:

我需要使用 Javascript 清除这段文本的部分内容:

<![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ]]>

更准确地说:

<![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" />

还有这个:

]]>

请注意,第一部分并不总是相同的(它来自 XML 提要)。

【问题讨论】:

  • 也许你应该解释一下大局。为什么您的 XML 解析器不自动删除 &lt;![CDATA[]]&gt;?为什么节点包含不完整的 HTML?如果第一部分发生变化,要删除的具体规格是什么?

标签: javascript xml cdata


【解决方案1】:

既然要提取CDATA标签之间的文本,我建议你使用简单的Regex来完成这项工作。

function removeCDATA(str) {
    var pattern = new RegExp(/\<!\[CDATA\[.*?\/>(.*?)\]\]\>/);
    var res = pattern.exec(str)[1];
    return res;
}

alert(removeCDATA('<![CDATA[<a href="http://example.com/20.0.0.1/13902/cf085cef63511989576657751aad3cda.jpg" width="3543" height="2362" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ]]>'))

jsfiddle:link

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2013-01-30
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多