Home > Blockchain >  Convert numeric string into an integer but ignore non-numeric strings
Convert numeric string into an integer but ignore non-numeric strings

Time:07-16

I created the following code because I'm getting values from an input that only accepts numbers and spaces, and I want to convert and add each number from the input while disregarding the spaces:

// variable textArea is the value from the input
let textArea = document.getElementById("numVal").value;
let regex = /^[0-9\s]*$/;
if(regex.test(textArea) == true) {
  let val = Number(textArea)  //Used this to convert the string into integer
  res1.innerHTML = textArea;
}
// The function that add all numbers is still lacking.

The numbers are collected, but when I add a space, it displays NaN. So, for example, if the textArea is 10, then it will display 10, but when the textArea is 10 (with space), it will display NaN

CodePudding user response:

Match all digits to get an array of digit strings, then turn each string into a number and add them up.

const { value } = document.getElementById("numVal");
if (/^[\d\s]*$/.test(value)) {
    const total = (value.match(/\d /g) || [])
        .map(Number)
        .reduce((a, b) => a   b, 0);
    res1.textContent = total;
}

It might be better UI-wise to prevent non-digits and non-spaces from being entered to begin with, rather than to fail to calculate when unexpected characters are encountered.

  • Related