In Javascript, you can use String.replace with a function as a parameter . This way you define match groups, and then you can replace each one individually.
Do you want to combine all spaces
\s+
and you need to combine everything inside the quotes
(('|")(?:[^\\]\\\2|.)*?\2)
so you combine it
var pattern = /\s+|(('|")(?:[^\\]\\\2|.)*?\2)/g
and you write a replace statement with an anonymous function as a parameter :
var filteredString = notFilteredString.replace(pattern, function(match, group1) { return group1 || "" })
At each match, the function is called to replace the string. A regular expression matches a space or content. The contents of the quote are wrapped as group1 , and the anonymous function returns group1 if group1 matches or nothing "" for spaces or another match.
source share