Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda