Convert text from div to number

Asked

Viewed 906 times

4

I’m trying to get the text of this structure:

<span id="our_price_display">R$ 71,90</span>

And I’d like you to return to me just the 71,90.

But in the structure I created, I can’t take the "R$" from the text and make it recognize only the numbers.

How could I make this conversation?

6 answers

3

You can use regex.

/\d+,\d+/g

Where:

  • \d+ = search by numbers
  • , = includes the comma
  • /g = global (across the string)

Example:

$("button").click(function(){
  var regex = /\d+,\d+/g;
  var texto = $("#our_price_display").text();
  var valor = regex.exec(texto);
  $("#resultado").text(valor.join(""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="our_price_display">R$ 71,90</span>
<br/>
<span id="resultado"></span>
<br/>
<button>Só valor</button>

  • Excuse my ignorance... $(Function(){ var valueDaDiv = $("#our_price_display"). Empty('/ d+, d+/g'); var myInteger = parseint(valueDaDiv); // console.log(myInteger); }); ?

  • @Juliorodrigues updated the answer with the explanation and an example.

3

var text = document.getElementById('our_price_display').innerText;

// APENAS DIGITOS E ,
var number = text.replace(/[^\d,]/g, '');
console.log(number);

// NUMERO PARA FLOAT (numeros presupostos que estão corretos em R$ > 1000,00)
var number = number.replace(',', '.');
console.log(parseFloat(number));
<span id="our_price_display">R$ 71,90</span>

3

var texto = document.getElementById('our_price_display').innerHTML;
var numero = texto.replace(/[^\d,]/g, '');
document.getElementById('resultado').innerHTML = numero;
<span id="our_price_display">R$ 71,90</span>
<div id="resultado"></div>

  • caracaaa man, thank you very much!

2

You can do it like this:

var price = document.getElementById('our_price_display');
var formattedPrice = price.innerHTML.replace(/[^\d,]/g, '');

console.log("Valor formatado:", formattedPrice);
<span id="our_price_display">R$ 71,90</span>

regex will clear the string of anything that is not numeric or comma.

1


Take the value of the element, then do a .split with javascript

var str = $("#our_price_display").html(); //pega valor todo
var res = str.split(" "); //seu valor você pega no res[1]

alert(res[1]);

0

The above answers already solve your problem well, but if you want to take a look at this library http://openexchangerates.github.io/accounting.js/.

I have used to convert text in USD in a game, it is very simple to use and has several monetary formats.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.