Why is this replace wrong?

1

I have the following function that brings a string as number in javascript. It can bring float value as 10.00 and int as 12. Why is it wrong? Give as replace is undefined in the line: text.replace("R$","");

function moneyTextToFloat(text){
  var cleanText = text.replace("R$","");
  cleanText = cleanText.replace(",",".");
  return parseFloat(cleanText);
}

Here is the javascript code, which was not mentioned above:

// faz o cálculo do total junto com o preço da taxa de entrega
function calculateTotalProductsEntrega()
{
  var produtos = document.getElementsByClassName("produto");
  var totalProdutos = 0;

  for(var pos = 0; pos < produtos.length; pos++)
  {

    // seleciona o preço
    var priceElements = produtos[pos].getElementsByClassName("precoproduto");
    var priceText = priceElements[0].innerHTML;
    var price = moneyTextToFloat(priceText);

    // seleciona a quantidade
    var qtyElements = produtos[pos].getElementsByClassName("quantidadeproduto");
    var qtyText = qtyElements[0].value;
    var quantity = moneyTextToFloat(qtyText);

    // pega a taxa de entrega prevista
    var shiptElements = produtos[pos].getElementsByClassName("taxaentrega");
    var shiptText = shiptElements[0].innerHTML;
    var shipt = moneyTextToFloat(shiptText);

    var subtotal = (quantity * price) + shipt;

    totalProdutos += subtotal;
  }

  return totalProdutos;
}

HTML IS THAT:

    
asked by anonymous 16.08.2017 / 18:59

1 answer

2

Hello,

Probably some non-String value is being passed, in this case, to prevent, convert the text parameter to string:

var cleanText = String(text).replace("R$","");

So you guarantee that it will always be string:)

    
17.08.2017 / 02:50