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

251
Visualizações
How to remove all the white spaces between two words?

I have an input field on which the user types the city name, but what if the user types the city like this:

"New    York     "
"  New York           "

I used the trim function but that did not work, any suggestion?

const city = "New         York     ";

console.log(city.trim());

How can I remove all the white spaces so I can save the city in the state as "New York"?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can also use replace to replace all consecutive space characters with one space:

const str = "New    York     "
"  New York           "

const res = str.replace(/\s+/gm, " ").trim()

console.log(res)

Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:

const str = "New    York     "
"  New York           "

const res = str.split(" ").filter(e=>e).join(" ")

console.log(res)

about 4 years ago · Juan Pablo Isaza Relatório

0

Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method

const city = "    New         York     ";

console.log(city.replace(/\s+/g, ' ').trim());

about 4 years ago · Juan Pablo Isaza 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