5

I have a String that I need to strip out all the spaces except for what between "". Here is the Regex that I am using to strip out spaces.

str.replace(/\s/g, "");

I cant seem to figure out how to get it to ignore spaces between quotes. Example

str = 'Here is my example "leave spaces here", ok im done'
Output = 'Hereismyexample"leave spaces here",okimdone'
Rob
  • 9,671
  • 10
  • 32
  • 53

3 Answers3

8
var output = input.split('"').map(function(v,i){
   return i%2 ? v : v.replace(/\s/g, "");
}).join('"');

Note that I renamed the variables because I can't write code with a variable whose name starts with an uppercase and especially when it's a standard constructor of the language. I'd suggest you stick with those guidelines when in doubt.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
8

Another way to do it. This has the assumption that no escaping is allowed within double quoted part of the string (e.g. no "leave \" space \" here"), but can be easily modified to allow it.

str.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) {
    if ($1) {
        return $1.replace(/\s/g, '');
    } else {
        return $2; 
    } 
});

Modified regex to allow escape of " within quoted string:

/([^"]+)|("(?:[^"\\]|\\.)+")/
nhahtdh
  • 52,949
  • 15
  • 113
  • 149
4

Rob, resurrecting this question because it had a simple solution that only required one replace call, not two. (Found your question while doing some research for a regex bounty quest.)

The regex is quite short:

"[^"]+"|( )

The left side of the alternation matches complete quoted strings. We will ignore these matches. The right side matches and captures spaces to Group 1, and we know they are the right spaced because they were not matched by the expression on the left.

Here is working code (see demo):

var subject = 'Here is my example "leave spaces here", ok im done';
var regex = /"[^"]+"|( )/g;
replaced = subject.replace(regex, function(m, group1) {
    if (group1 == "" ) return m;
    else return "";
});
document.write(replaced);

Reference

  1. How to match pattern except in situations s1, s2, s3
  2. How to match a pattern unless...
Community
  • 1
  • 1
zx81
  • 38,175
  • 8
  • 76
  • 97