Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda