Super Cool Handsome Gel Boy Super Cool Handsome Gel Boy - 1 month ago 4x
Javascript Question

How can I use Javascript RegExp to escape brackets?

I am unable to find any resources on the web for my case.

So I tried to use the following RegExp to escape the brackets and things inside.
Here is the example string:

hjdsoghbesi (saeogbesor) serogberso ersberawsewf(edsrgb) sfdrobersb ouersber

So I want the result code to be

hjdsoghbesi serogberso ersberawsewf sfdrobersb ouersber

I tried to use the following:


However, this focused on the very first open bracket and the very last close bracket and gave me:

hjdsoghbesi sfdrobersb ouersber

How can I achieve the result that I wanted?

If you intend to answer, please tell me why your RegExp can achieve my purpose as I am unfamiliar with RegExp.


Use non-greedy quantifiers:

var str = "hjdsoghbesi (saeogbesor) serogberso ersberawsewf(edsrgb) sfdrobersb ouersber";
console.log(str.replace(/\(.*?\)/g, ""));

* is greedy, it will match as many characters as possible.

*? is lazy, it will match as few as possible.