Replacing characters in a string

Asked

Viewed 85 times

2

I have a string to be passed through the form and would like to replace some characters of it so that it is in the form of numeral:

if(form1.autonomoBonusBruto.value.includes("R$")){
            form1.autonomoBonusBruto.value.replace("R$","");
            alert(form1.autonomoBonusBruto.value);
        }
  • And what’s the problem?

  • It’s not working, I don’t know why, I put Alert to see what the variable looks like after replace, but it’s not taking out the "R$"

  • You know if you can even get into the IF?

2 answers

2


The problem is that you are not assigning the value to the variable. O replace() does not change the variable, it manipulates the value and returns that new value. If you do not store it somewhere, it is lost. This is how it works:

if (form1.autonomoBonusBruto.value.includes("R$")){
    form1.autonomoBonusBruto.value = form1.autonomoBonusBruto.value.replace("R$", "");
    alert(form1.autonomoBonusBruto.value);
}
<form name = "form1">
    <input name = "autonomoBonusBruto" value = "R$">
</form>

I put in the Github for future reference.

1

Dude, there is no problem with this code. Your variable contains "R$" and you replace it with "". What you would like to appear on Alert()?

if (form1.autonomoBonusBruto.value.includes("R$")){
    form1.autonomoBonusBruto.value = form1.autonomoBonusBruto.value.replace("R$", "");
    alert(form1.autonomoBonusBruto.value);
}
<form name="form1">
  <input name="autonomoBonusBruto" value="R$10,00">
</form>

  • Do you think my answer is the question? Or did you just copy my answer as a solution?

Browser other questions tagged

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