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

242
Visualizações
Remove whitespace from spaced-out word?

Assume the following string:

hello world, h e l l o! hi. I am happy to see you!

Is there a way to remove whitespace in the spaced out word, like so?:

hello world, hello! hi. I am happy to see you!

I tried [^ ]+(\s) but the capture group matches all spaces. thank you.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

One regex approach might be:

var input = "hello world, h e l l o! hi. I am happy to see you!";
var output = input.replace(/(?<=\b\w)\s+(?=\w\b)/g, "");
console.log(output);

Here is an explanation of the regex pattern, which targets whitespace situated in between two standalone single word characters on both sides:

(?<=\b\w)  assert that what precedes is a single character
\s+        match one or more whitespace characters
(?=\w\b)   assert that what follows is a single character
over 4 years ago · Santiago Trujillo Relatório

0

As you have tagged pcre, another option could be:

(?:\b\w\b|\G(?!^))\K\h(?=\w\b)

Explanation

  • (?: Non capture group for the alternation |
    • \b\w\b Match a single word char between word boundaries
    • | Or
    • \G(?!^) Assert the position at the end of the previous match, not at the start
  • ) Close non capture group
  • \K\h Forget what is matches so far, and match a single horizontal whitespace char
  • (?=\w\b) Positive lookahead, assert a single word char followed by a wordboundary to the right

Regex demo

In the replacement use an empty string.


Another option could be matching at least 2 chars in a sequence of single word chars, and in the replacement remove the space.

Note that \s could also match a newline.

const regex = /\b\w(?: \w)+\b/g
const str = "hello world, h e l l o! hi. I am happy to see you!";
let res = str.replace(regex, m => m.replace(/ /g, ''));
console.log(res);

over 4 years ago · Santiago Trujillo 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