简体   繁体   中英

How to remove   with javascript this case?

I have a question.

<table id="mytable">
 <tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
  <td>&nbsp;</td>
  <td>4</td>
 </tr>
 <tr>
  <td>5</td>
  <td>6</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>7</td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>8</td>
  <td>9</td>
  <td>10</td>
 </tr>
</table>

and here is script.

var table = document.getElementById("mytable");
for (var i = 0; i < 3; i++) {
  for (var k = 0; k < 5; k++) {
    var str = table.rows[i].cells[k].innerHTML;
    alert(str);
  }
};

I try to code this

alert(str.replace(/(&nbsp;)*/g,''))

but then empty alert box show up.

I want to pop up cells value expect &nb sp; and empty box.


显示“&nbsp” show up '&nbsp'. I don't want it.

出现 '' show up "". I don't want it.

我要这个! I want this. Thank you for comment.

        var str = table.rows[i].cells[k].innerHTML.replace(/[&]nbsp[;]/gi,"");
         if (str.length > 0) {
          alert(str);
        }

Replace the innerHtml of td with empty string by Regex and check the length of string. If the length is bigger than 0, alert that.

 var table = document.getElementById("mytable"); for (var i = 0; i < 3; i++) { for (var k = 0; k < 5; k++) { var str = table.rows[i].cells[k].innerHTML; str = str.replace(/(&nbsp;)*/g, ''); if (str.length) alert(str); } }; 
 <table id="mytable"> <tr> <td>1</td> <td>2</td> <td>3</td> <td>&nbsp;</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>7</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>8</td> <td>9</td> <td>10</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM