Home > Back-end >  Calculation not being performe properly in JavaScript
Calculation not being performe properly in JavaScript

Time:06-30

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   "%");
}

CodePudding user response:

You're matching the result, whose matched values may be a mix of changed or unchanged characters. Matched values in your source will all be changed.

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

To: let x = (json.charsEntered.match(/[etET]/g)||[]).length;

CodePudding user response:

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);
  • Related