2009-08-20 71 views
0

我在頁面上有一些文本,我想找到並刪除括號中的任何文本。 例如:在jQuery中查找包含在括號中的文本

<td>here is [my text] that I want to look at</td> 

所以我想抓住該文本(我的文本),它保存在一個變量,並從那裏將其刪除。

回答

1

如果你使用jQuery,你可以在$('body')。text()上使用正則表達式,如\[(.+)\]

編輯:對不起,我可能會跳槍給你一個這個答案。繼續考慮更多幾分鐘,然後嘗試用更多的信息來更新它。

1

你可能會發現這個任務不是那麼簡單。如果你在文本上的控制,在它發送到Web瀏覽器,你可以把它放到一個<span class='bracket'>[my text]</span>中的文本,那麼你可以很容易地做這樣的事情用jQuery:

$(".bracket").each(function() { 
    // store the data from $(this).text(); 
}).remove(); 

這可以通過定期做表達式和jQuery的,但也有可能攀升處理像<input name='test[one][]' />屬性中的文本問題的「簡單」的正則表達式將做這樣的事情:

$("td").each(function() { 
    var $this = $(this); 

    var html = $this.html(); 
    var bracketText = []; 

    // match all bracketed text in the html - replace with an empty string 
    // but push the text on to the array. 

    html = html.replace(/\[([^\]]+)\]/g, function() { 
    bracketText.push(arguments[1]); 
    return ""; 
    }); 

    // put the new html in away and save the data for later 
    $this.html(html).data("bracketText", bracketText); 
}); 

有沒有,如果你這樣做太大的危險'確保你不會在文本標籤內部有[]

+0

這是什麼樣的我在想,除了試圖想想如何將它推廣到不僅僅是一組特定的標籤(如果你不知道包含括號內文本的標籤是什麼)。非常好。 – theIV 2009-08-20 01:54:17

0

最後我做了以下內容:

 $('#formQuizAnswers td.question').each(function(){ 
     var header = $(this).text().match(/-.*-/); 
     $(this).text($(this).text().replace(header,'')); 
}); 

我改變了我的文字我搜索到有破折號周圍IE -My文本的

+0

我不會在這裏使用貪婪的量詞。那怎麼樣 - '/ - [^ - ] * - /' – kangax 2009-08-20 04:31:09

相關問題