Search code examples
javascriptnode.jsregexpcre

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.


Solution

  • 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