1

I want to hide a substring in a table cell. Let's assume the table looks like this:

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

How can I use jQuery (and CSS) to hide the [100,100] part of cell 2 and the [130, 70] part of cell 3?

I found this solution in another answer for a similar problem:

<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>');
})

But I think I would need a regex solution since the contents of the [ ] part can be different? or is there a better iea?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TDeJesus
  • 11
  • 2

3 Answers3

2

You are correct about needing a regex. This should work:

<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, '');
})
Brian H
  • 1,033
  • 2
  • 9
  • 28
0

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

Brian's answer removes the text instead of hiding it (which is more cost savy, if you do not need that text for later). If in any case, you really need to hide it for future reference, this will do the trick. I also tend to use more precise regexes. Brian's will remove everything between square brackets. The upper one will match only if there are two numbers separated by comma, between them.

Regex reference -> https://www.w3schools.com/jsref/jsref_obj_regexp.asp

Capturing groups explained -> https://stackoverflow.com/a/6419076/7081773

Community
  • 1
  • 1
Viliam Aboši
  • 447
  • 2
  • 14
0

Since you asked about table cells, you want to zero in and limit to just your <td> just in case you have similar text elsewhere:

$( 'td' ).each(function() {
    var currentText = $( this ).text();
    var newText = currentText.replace(/\[.+\]/g, '');
    $( this ).text( newText );
});
Paul Sturm
  • 2,118
  • 1
  • 18
  • 23