我写了一小段代码从rss页面检索新闻。下面是代码:
this.loadRecentNews = function loadRecentNews() {
$.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) {
$(data).find("item").each(function () {
var el = $(this);
console.log("------------------------");
console.log("Title : " + el.find("title").text());
console.log("Link : " + el.find("link").text());
console.log("Description: " + el.find("description").text());
console.log("Date: " + el.find("pubDate").text());
});
});
};
输出如下:
Title : Example of title
Link : http://www.example.com
Description : Example of <<bb>>Description</b> containing <> tag..
Date : Example of date
我的问题是,我想只提取描述值的文本来构建包含此文本的新Json对象。
我怎样才能只提取没有<>值的文本?
既然你正在使用jQuery,你可以使用它的.text()
方法。
var beforeText = "Example of <b>Description</b>" ;
var afterText = $("<p>").html(beforeText).text() ;
使用jQuery创建一个新的HTML元素(从未添加到页面中)并更新其innerHTML,然后使用.text()
仅获取文本。
另一个(风险较大的)选项是用一个空字符串替换<
和>
之间的任何内容的正则表达式:
var afterText = beforeText.replace(/<[^>]*>+/g, "")