2013-03-07 108 views
0

我正在解析我的網站上的XML源,其中一個源以下列格式顯示:新聞報道標題(2013年1月15日)。我想刪除括號內的所有內容。使用javascript刪除所有內容和內容

我存儲在整個字符串中的一個變量,像這樣:var title = $(this).text();

然後我使用jQuery的每個循環遍歷每個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); 

這很好,但我該如何刪除這些形式的字符串?

+0

所以,你有什麼話,以消除此內容試過嗎? – 2013-03-07 21:01:24

+0

我對RegEx並不熟悉,所以我還沒有嘗試過使用它,但是... – JCHASE11 2013-03-07 21:02:45

回答

1

您可以將此用作基礎,並根據需要爲日期優化正則表達式。

$('h4 a').each(function() { 
    var new_text = $(this).text().replace(/((\s*)\((.*)\))/, ""); 
    $(this).text(new_text); 
}); 
+0

這太好了,謝謝Derek! – JCHASE11 2013-03-07 21:13:13

0

如果你有信心,遊戲將遵循相同的模式,你不需要使用正則表達式來實現:

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

$('h4 a').each(function() { 
    $(this).text(removeDate($(this).text()); 
});