Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!