Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda