Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression for Removing all Spaces except for what between double quotes

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'
like image 434
Rob Avatar asked Jan 26 '13 18:01

Rob


2 Answers

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:

/([^"]+)|("(?:[^"\\]|\\.)+")/
like image 199
nhahtdh Avatar answered Sep 24 '22 13:09

nhahtdh


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.

like image 45
Denys Séguret Avatar answered Sep 24 '22 13:09

Denys Séguret