Why is this replace wrong?

Asked

Viewed 133 times

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? Gives as replace is Undefined on 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;
}

THE HTML IS THAT: inserir a descrição da imagem aqui

  • What are you calling that function? And that line text.replace("R$",""); is so alone without being used?

  • Not the top line talks about the error itself

  • What are you calling that function?

  • Well I’ll put in the answer the javascript

  • You can ask the question that we help to format. Click on [Edit].

  • 2

    If the variable text has not the method replace is because it is not a string. Review what you pass to the function.

  • As already mentioned by @Renan if this happens it is because "text" is not string. Make text.toString(). replace("R$", "")

  • From what I see moneyTextToFloat will always receive a string. You can make an example here or in a jsFiddle that plays the problem online?

Show 3 more comments

1 answer

2


Hello,

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

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

So you guarantee it will always be string :)

Browser other questions tagged

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