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

112
Visualizações
I need to filter hyphen(-) and space(" ") in my string, what am I doing wrong?

This is the code I am using (but it only works for hyphens not for spaces)

console.log(
    "some - text".replace(/\s\-/g, '').toLowerCase()
)

Can anyone point out what is wrong in this RegEx ?

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

0

The regex you have removes the space and the dash, leaving the second space

You need other regex to remove all spaces

console.log(
    "some - text".replace(/\s\-/g, '') // space and dash
)

console.log(
    "some - text".replace(/\s-\s/g, '') // space before and after a dash
)


console.log(
    "some     -        text".replace(/\s+\-\s+/g, '') // any whitespace before and after
)


console.log(
    "so- me     -        te-xt".replace(/\s|-/g, '') // all spaces and all dashes, can be written as a acharacter class [\s-]
)

about 4 years ago · Juan Pablo Isaza Relatório

0

Use\W for non-word character:

console.log("some - text".replace(/\W/g, '').toLowerCase())
about 4 years ago · Juan Pablo Isaza Relatório

0

Your regex is matching "(1 occurrence of some space)(definitely followed by 1 occurrence of ad ash)". You want it to match any occurrence of those, so use a character class in your regex (see: MDN WebDocs: JavaScript Character Classes, with brackets, /[\s\-]/g, like so:

console.log(
    "some - text".replace(/[\s-]/g, '').toLowerCase()
)

Want to replace another character? Just throw it into the class and you're good to go.

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