Problem adding millions to a table replace jquery

2

Currently I take all the values of the second column sums and I remove the "$" and ".", only works when they are 6-digit numbers by placing 7-digit numbers in the table the sum is wrong, What can be done? in my opinion I am doing wrong replace thank you.

var Total = 0;
$('#table_vehiculos tbody > tr').each(function() {
  let precio = $(this).find('td:eq(1)').text().replace(/\$/, '').replace(/\./, '');
  Total += Number(precio);
});
alert(Total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_vehiculos">
  <thead>
    <tr>
      <th>Modelo</th>
      <th>Precio</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>chevrolet</td>
      <td>$2.000.000</td>
    </tr>
    <tr>
      <td>suzuki</td>
      <td>$6.000.000</td>
    </tr>
  </tbody>
</table>
    
asked by Javier Antonio Aguayo Aguilar 14.07.2017 в 22:13
source

2 answers

1

since you are using .replace() with Regex the way you do it can be simplified, if you have:

$(this).find('td:eq(1)').text().replace(/\$/, '').replace(/\./, '');

can be done this way:

$(this).find('td:eq(1)').text().replace(/(\$|\.)/g, '');

I am indicating that all $ or . of the text is replaced, but I add g so that the search is global, that is, that searches for all matches

var Total = 0;
$('#table_vehiculos tbody > tr').each(function() {
  let precio = $(this).find('td:eq(1)').text().replace(/(\$|\.)/g, '');
  Total += Number(precio);
});
alert(Total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_vehiculos">
  <thead>
    <tr>
      <th>Modelo</th>
      <th>Precio</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>chevrolet</td>
      <td>$2.000.000</td>
    </tr>
    <tr>
      <td>suzuki</td>
      <td>$6.000.000</td>
    </tr>
  </tbody>
</table>
    
answered by 14.07.2017 / 22:20
source
0

You can also use RegExp :

var Total = 0;
var expresion_regular = RegExp('[\$,\.]', 'g');

$('#table_vehiculos tbody > tr').each(function() {
  let precio = $(this).find('td:eq(1)').text().replace(expresion_regular, '');
  Total += Number(precio);
});
alert(Total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_vehiculos">
  <thead>
    <tr>
      <th>Modelo</th>
      <th>Precio</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>chevrolet</td>
      <td>$2.000.000</td>
    </tr>
    <tr>
      <td>suzuki</td>
      <td>$6.000.000</td>
    </tr>
  </tbody>
</table>

By the way, g (global match) is used to replace all occurrences. I have taken the regular expression out of the loop since it is not necessary to compile it in each iteration.

    
answered by 14.07.2017 в 22:25