Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...