Replace is not a function

0

I created a script to insert a div into the cart in my store, but it is giving it an error in the replace function. Would anyone know why?

var $JQuery = jQuery.noConflict();
$JQuery(function(){ 
var ValorFreteGratis = 299;
var PrecoTotal = '{{order_total}}';
var QuantoFalta = ValorFreteGratis - PrecoTotal;
var NumeroComVirgula = QuantoFalta.replace(".", ",");
if(PrecoTotal < ValorFreteGratis){
$JQuery('<div class="msg-free_shipping"> <p><span class="warning">EI!!:</span> Comprando mais R$' + NumeroComVirgula.toFixed(2) + ' <span class="restante">você aproveita o <strong>FRETE GRÁTIS</strong> nas compras acima de R$<span class="valor-gratis">' + ValorFreteGratis + '</span></p> </div>').insertAfter('form#cart_update_post');}});

You get the error: "Uncaught TypeError: How much is missing is not a function"

    
asked by anonymous 17.02.2017 / 17:26

3 answers

5

QuantoFalta is the result of a mathematical operation, so it is not a String . Use toString to transform it:

 ...
 ... QuantoFalta.toString().replace(...
 ...
    
17.02.2017 / 17:35
2

Your problem is typed (you can tell by TypeError ), as you are doing a subtraction, the whole result becomes number , so the replace function does not exist.

var x = 10 - 5; // deve dar 5
console.log(x) // 5
console.log(typeof x) // number
x.replace(5, 10) // Uncaught TypeError

What can be done is to change the type of the variable, using String(valor) :

    var x = 10 - 5; // deve dar 5
    console.log(x) // 5
    
    x = String(x).replace('5', 'agora foi') // note o uso do String(x)
    console.log(x) // "agora foi"
    
    // O string pode ser feito na conta também
    // Ex:
    var y = String(10 - 5)
    console.log(y)
    

Generally these errors cause confusion because Javascript is not a well-typed language, it is not necessary to make this explicit during use. And another thing that can also cause problems is, you can subtract / multiply / divide strings and they will become number , but you can not add them, since it's the same character used to concatenate, this another thing that can create this kind of confusion.

console.log(typeof ('10' - '5')) // number (5)
console.log(typeof (10 + 5)) // number (15)
console.log(typeof ('10' + 5)) // string ('105') 
console.log(typeof (10 + '5')) // string ('105')
console.log(typeof ('10' + '5')) // string ('105')
    
17.02.2017 / 17:46
1

replace can only be given with String. Change to:

var numeroComVirgula = String(QuantoFalta).replace('.',',')

    
17.02.2017 / 17:39