Get data on page by javascript and convert it to integer

2

This with a problem, when I get a number inside a span by javascript I try to convert it to int with parseInt, but nothing. For if I try to make a sum with another number it ends up concatenated. and if I convert with parseInt it will appear 'NAN'.

HTML:

<div id="qualquer"><span>5</span></div>

Javascript with Jquery:

numeroRecuperado = parseInt($('#qualquer span').text().replace(/[\d]/g, ''));
numeroQualquer = 5;

total = numeroRecuperado + numeroQualquer;

$("#qualquer span").text(total);

As a result it appears NAN.

    
asked by anonymous 08.10.2015 / 17:34

3 answers

2

I notice from your code that there is an error. You used the regular expression /[\d]/g . However, this regular expression causes numeric values to be captured. That is, you are asking to overwrite numeric values for nothing.

Example:

document.write('teste 1 teste'.replace(/[\d]/g, ''));

The solution to your problem would be to do something like this:

var valor = document.querySelector('#id_do_span').innerHTML

var outro_valor = 15;

parseInt(valor) + outro_valor

See this working on JSFIDDLE

If you want to use regular expressions to get only numeric values, use the regular expression \D+ (non-numeric).

See:

var string = 'teste 15 teste';

document.write(string.replace(/\D+/g, ''));

Hint : As a suggestion, I suggest that you use the values of data of jQuery . You can set the value Number normally there because it is not saved as String . This way you avoid conversions of unnecessary values.

Example:

$(function ()
{
    $('body').html($('#meu_span').data('number') + 3);
})
<span id="meu_span" data-number='3'>3</span>
    
08.10.2015 / 17:38
3

Follow the solution on top of your code:

numeroRecuperado = parseInt($('#qualquer span').text().replace(/\D/g,''));
numeroQualquer = 5;

total = numeroRecuperado + numeroQualquer;

$("#qualquer span").text(total);

follow fiddle

    
08.10.2015 / 17:48
2

To avoid empty-space problems I use this way

numeroRecuperado = $('#qualquer span').text().replace(/\D/g, ''); // Remove o que não é número
numeroRecuperado = parseInt(numeroRecuperado) | 0; // o | 0 evita que uma falha na conversão retorne um NaN
numeroQualquer = 5;

total = numeroRecuperado + numeroQualquer;

$("#qualquer span").text(total);
    
08.10.2015 / 18:53