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

344
Visualizações
Regexp remove duplicate whitespace leaving only 1 or 2 occurences

I'm making a simple comment box and I want to remove excess whitespace by replacing the whitespace with only 1 or 2 tokens, whether they be newlines or spaces.

(\s){2,} is what I have so far. However, I want to leave users with the ability to double-space their comments, and replacing this with $1, the first capture group, would reduce their lines to a single space.

So basically,

If I have 1 space or newline, then replace it with 1 space or newline.

If I have more than 1 spaces or newlines, then replace it with exactly 2 spaces or newlines.

Thanks.

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

0

You can replace matches of

(?<=\s)\s+/

with a space.

Demo

The regular expression reads, "Match one or more whitespace characters that are preceded by a whitespace character". (?<=\s) is a positive lookbehind.

Note that the characters below marked '^' are matched by the regular expression and then replaced by a single space:

Two spaces  then three   then four    then five\n    then none
           ^           ^^          ^^^           ^^^^

When matches are replaced by a space the string becomes the following.

Two spaces  then three  then four  then five\n then none

Notice that the space following the newline character is the first of four whitespace characters that are matched.

about 4 years ago · Juan Pablo Isaza Relatório

0

text=document.getElemntById('comment_text_input').value
while(text.indexOf('\n\n\n')!=-1||text.indexOf('   ')!=-1) {
 text=text.replaceAll('\n\n\n','\n\n') //it makes '\n\n\n\n\n\n' to '\n\n\n\n', the next round '\n\n\n' and finally '\n\n'
 text=text.replaceAll('   ','  ') // the same with the newlines
  }
document.getElemntById('comment_text_input').value=text

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use

.replace(/(\s{2})\s+/g, '$1')

Details:

  • (\s{2}) - Group 1: two whitespace chars
  • \s+ - one or more whitespaces.

See the JavaScript demo:

const text = 'Abc 123\n DEF 234\n      New line'
console.log(text.replace(/(\s{2})\s+/g, '$1'));

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