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

218
Visualizações
Regex to remove leading and trailing special characters and spaces from string

I'm trying to find a regex to remove all leading/trailing spaces as well as all leading/trailing special characters.

If I have the string:

test = '~!#@$@  hello this is a #! test  ^^#!^^    '

I'd like it to return as:

'hello this is a #! test'

So special characters and spaces in between the first and last letter are preserved, but all leading/trailing ones are cut out. Right now I have this:

test.replace(/[^a-zA-Z ]/g,"").replace(/^\s+|\s+$/g, "")

which returns:

'hello this is a  test'

so it is removing all special characters and leading/trailing spaces. How can I preserve that "#!" between "a" and "test"?

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

0

By using the unicode flag u you can use the Unicode Categories for Letters \p{L} and Numbers \p{N} in a negative character class [^...].
And match them at the start ^ or | at the end $ to get anything that's not a letter or number and is trailing or leading.

Pattern:

^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$

Test Snippet:

let test = '~!#@$@  hello this is a #! test  ^^#!^^    ';

test = test.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');

document.write('['+test+']');

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