0

我正在解析我网站上的 XML 提要,其中一个提要以以下格式显示: 新闻故事标题(2013 年 1 月 15 日)。我想删除括号和其中的所有内容。

我将整个字符串存储在一个变量中,如下所示: var title = $(this).text();

然后我使用 jquery 的 each 来遍历每个 RSS 标题,如下所示:

$('h4 a').each(function() {

      var title = $(this).text();

});

然后我可以使用正则表达式来获取括号内的内容并像这样警告它:

var title = $(this).text();
var regex = new RegExp('\\((.*?)\\)', 'g');
var match, matches = [];
while(match = regex.exec(title))
    matches.push(match[1]);
alert(matches);

这很好,但我将如何从字符串中删除这些?

4

2 回答 2

1

您可以将其用作基础,并根据日期的需要细化您的正则表达式。

$('h4 a').each(function() {
    var new_text = $(this).text().replace(/((\s*)\((.*)\))/, "");
    $(this).text(new_text);
});
于 2013-03-07T21:11:33.930 回答
0

如果您确信标题将遵循相同的模式,则无需使用正则表达式来完成此操作:

function removeDate(title) {
    var index = title.lastIndexOf('(');
    return title.substr(0, index).trim();
}

$('h4 a').each(function() {
    $(this).text(removeDate($(this).text());
});
于 2013-03-07T21:14:11.103 回答