Regex to remove spaces between '[' and ']'
Asked Answered
K

4

8

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

Katykatya answered 20/5, 2013 at 6:56 Comment(3)
I don't think you can do this in one step. You have to extract the contents of the brackets, remove spaces from that, and then substitute that back in.Instantaneous
Can the brackets be nested? If so, you can't do it with a JavaScript regex. If not, no problem (if brackets are always correctly balanced).Mcnamee
It wont be nested as of now. So looks simple.Katykatya
M
19

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.
Mcnamee answered 20/5, 2013 at 7:29 Comment(0)
B
4

Try

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

Demo: Fiddle

Boscage answered 20/5, 2013 at 7:2 Comment(1)
Thanks Arun. Can you explain a bit about the above expression?Katykatya
P
0

Slight adaptation so you can use in in [Visual Studio Code] or [SSMS] with [SQL] queries, remember to hit the regex option on the find/replace dialog

\s+(?=[^[\]]*\])

SSMS Find/replace dialog

Note - screenshot shows the spaces being replaced with "_"

Pase answered 7/12, 2023 at 11:36 Comment(0)
H
-5

You can use this

"[first name] + [ last name ] + calculateAge()".gsub(/\s+/, "")

This works in ruby

Heyde answered 20/5, 2013 at 7:23 Comment(1)
Did you even test that? The question is about JavaScript, not Ruby, and in Ruby, you get [firstname]+[lastname]+calculateAge() as a result.Mcnamee

© 2022 - 2024 — McMap. All rights reserved.