Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!