2017-04-07 185 views
1

我想隱藏表格單元格中的子字符串。讓我們假設表看起來像這樣:jQuery隱藏表格單元格中的子字符串

<div id="table"> 
    <table> 
    <tr> 
     <td> Blah </td> 
     <td> Blah [100, 100]</td> 
     <td> Blah [130, 70]</td> 
    </tr> 
    </table> 
</div> 

我如何使用jQuery(和CSS)隱藏單元2,[130,70]小區3的一部分的[100,100]部分?

我發現了另一個答案這個解決方案類似的問題:

<div class="text">Good Stuff Hide Me</div> 
<div class="text">Great Stuff Hide Me</div> 
<div class="text">Best Stuff Hide Me</div> 

$('div.text').html(function (i, t) { 
    return t.replace('Hide Me', '<span class="hidden">Hide Me</span>'); 
}) 

但我想我會需要,因爲[]部分內容的正則表達式的解決方案可以是不同的?還是有更好的iea?

回答

2

你對需要正則表達式是正確的。這應該工作:

<div class="text">Good Stuff [100]</div> 
<div class="text">Great Stuff[100,010]</div> 
<div class="text">Best Stuff[70, 130, 180]</div> 

$('div.text').html(function (i, t) { 
    return t.replace(/\[.*\]/g, ''); 
}) 
0

t.replace(/(\s*\[s*\d+\s*,\s*\d+\s*\])/, '<span class="hidden">$1</span>')

Brian的回答中刪除,而不是隱藏它的文本(這是更具成本薩維,如果你不需要的文本後面再說)。如果在任何情況下,你真的需要隱藏它以備將來參考,這將成爲訣竅。我也傾向於使用更精確的正則表達式。布萊恩將刪除方括號內的所有內容。只有當兩個數字之間用逗號分隔時,上面的那個纔會匹配。

正則表達式參考 - >https://www.w3schools.com/jsref/jsref_obj_regexp.asp

捕獲組說明 - >https://stackoverflow.com/a/6419076/7081773

0

既然你問到表格單元格,要在零和限制只是你<td>,以防萬一你有其他地方的類似文本:

$('td').each(function() { 
    var currentText = $(this).text(); 
    var newText = currentText.replace(/\[.+\]/g, ''); 
    $(this).text(newText); 
}); 
相關問題