Regex for replacing spaces not between quotation marks

Viewed 188

I'd like to remove all whitespaces from a given string like this

const mystring = `
   This is an example string with 'single quotes' and "big quotes"!
   No that "this \" special \" " notation with escaped quotes should also not be matched
`;

that are not between quotes (" or ') to get something like this

const result = `Thisisanexamplestringwith'single quotes'and"big quotes"!Nothat"this \" special \" "notationwithescapedquotesshouldalsonotbematched`;

Some better examples that are easier to understand:

  • This is an example with "quotes and spaces"! > Thisisanexamplewith"quotes and spaces"!

  • Second example for 'quotes and spaces' > Secondexamplefor'quotes and spaces'

  • test "a \"b c \" d e" > testa \"b c \" d e"

I guess the principle is easy to understand.

I want to replace via Regular Expression without additional javascript code. Since I haven't really worked with Regex much and I'm totally desperate after a full day on Regex101.com, I decided to ask for help on SO.


Any help how to go on would be really appreciated. Thanks in advance!


What I've done so far:

I'm pretty sure using Regex's Lookahead/Lookbehind matcher will do the job but I guess I'm not really using it as I should...

  • \s(?<!") regex #1
  • \s(?<="[^"].) regex #2
  • \s+(?=(?:(?:\.|[^"\])"(?:\.|[^"\])")*) regex #3
0 Answers
Related