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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…