Clean away CDATA from string

六月ゝ 毕业季﹏ 提交于 2021-02-08 10:38:13

问题


I need to clean away parts of this block of text using 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. ]]>

More precisely this:

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

and this:

]]>

Please note that the first part is not always the same (its from an XML-feed).


回答1:


Since you want to extract the text between CDATA tags, I suggest you to use simple Regex to do the job.

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



来源:https://stackoverflow.com/questions/23634491/clean-away-cdata-from-string

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