Remove whitespace from spaced-out word?

Viewed 58

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.

2 Answers

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

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);

Related