Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove spaces between '[' and ']'

I have been breaking my head on this for sometime now. In javascript I have a string expression where I need to remove the spaces between '[' and ']'.

For example the expression can be :-

"[first name] + [ last name ] + calculateAge()"

I want it to become :-

"[firstname] + [lastname] + calculateAge()"

I tried something from the following stackoverflow question for square brackets but didn't quite get there. How do I make the regex in that question, work for square brackets too?

Can anyone help?

Thanks, AJ

like image 506
Akshat Avatar asked May 20 '13 06:05

Akshat


2 Answers

If brackets are always balanced correctly and if they are never nested, then you can do it:

result = subject.replace(/\s+(?=[^[\]]*\])/g, "");

This replaces whitespace characters if and only if there is a ] character ahead in the string with no intervening [ or ] characters.

Explanation:

\s+       # Match whitespace characters
(?=       # if it's possible to match the following here:
 [^[\]]*  # Any number of characters except [ or ]
 \]       # followed by a ].
)         # End of lookahead assertion.
like image 88
Tim Pietzcker Avatar answered Sep 21 '22 19:09

Tim Pietzcker


Try

"[first name] + [ last name ] + calculateAge()".replace(/\[.*?\]/g, function(string) {
    return string.replace(/\s/g, '');
})

Demo: Fiddle

like image 26
Arun P Johny Avatar answered Sep 22 '22 19:09

Arun P Johny