Skip to content
Advertisement

Calculation not being performe properly in JavaScript

I have the following code that is converting characters entered in an input field into other characters (namely, entering an e or and E and converting it to a 3, likewise for a t or T into a 7).
I am also calculating the percentage of the characters that were converted, but my calculation is not being performed properly and was wondering if someone can help with this.
For example, if someone enters in a string like 373, it will not convert the characters (as expected), but the number of converted characters will be 3 when they should be 0 instead.

function ReplaceChars() {

  var json         = JSON.parse(localStorage.getItem("registration"));
  var characters   = json['charsEntered'];
  var total        = "";
  var convertedPct = 0;

  const result = characters
      .replaceAll(/e|E/g,"3")
      .replaceAll(/t|T/g,"7")

  total = characters.length;

  let x = Number((result.match(/3|7/g)||[]).length);
  let y = Number(total);

  convertedPct      = (x/y)*100
  roundedPercentage = convertedPct.toFixed(2);

  $("#charsConverted").val(result);
  $("#convertedChars").val(x);
  $("#totalChars").val(y);
  $("#pctChars").val(roundedPercentage + "%");
}

Advertisement

Answer

You can pass a function when replacing characters that would also count

  let totalReplacements = 0;

  characters
    .replace(/e|E/g, () => {
      totalReplacements ++; 
      return '3';
    })
    .replace(/t|T/g, () => {
      totalReplacements ++; 
      return '7'
    })

Now totalRepalcements will hold the total number of replacements that have been done.

  convertedPct      = (totalReplacements / characters.length) * 100
  roundedPercentage = convertedPct.toFixed(2);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement