Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert numeric string into an integer but ignore non-numeric strings

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading