Trim jquery td table

1
<table id="table">
 <thead>
    <tr>
        <th>Nombre</th>
        <th>Apellido</th>
        <th>Edad</th>
    </tr>
 </thead>
<tbody>
    <tr>
        <td>Juan</td>
        <td class="td_apellido">   Perez   </td><!-- espacios en blanco necesito retirarlos-->
        <td>25</td>
    </tr>

    <tr>
        <td>Jorge</td>
        <td class="td_apellido">   Aguilar   </td><!-- espacios en blanco necesito retirarlos-->
        <td>15</td>
    </tr>

</tbody>
</table>

I have a td with blank spaces which I tried to use $ .trim but without results:

$("#table").find("tbody").find("td").each(function(){ 
    if ($(this).attr("class") == "td_apellido") {
        $(this).text().trim();
    }
 });
    
asked by Javier Antonio Aguayo Aguilar 07.06.2017 в 18:48
source

2 answers

3

You just need to assign the trim result back to the original cell:

$("#table").find("tbody").find("td").each(function(){ 
    if ($(this).attr("class") == "td_apellido") {
       $(this).text($(this).text().trim());
    }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
 <thead>
    <tr>
        <th>Nombre</th>
        <th>Apellido</th>
        <th>Edad</th>
    </tr>
 </thead>
<tbody>
    <tr>
        <td>Juan</td>
        <td class="td_apellido">   Perez   </td><!-- espacios en blanco necesito retirarlos-->
        <td>25</td>
    </tr>

    <tr>
        <td>Jorge</td>
        <td class="td_apellido">   Aguilar   </td><!-- espacios en blanco necesito retirarlos-->
        <td>15</td>
    </tr>

</tbody>
</table>
    
answered by 07.06.2017 / 18:52
source
0

You could also create a separate function that removes white space.

function quitarEspacios($cadena){
$cadena = str_replace(' ', '', $cadena);
return $cadena;
}
    
answered by 07.06.2017 в 18:58