0

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

I want the result code to be

hjdsoghbesi serogberso ersberawsewf sfdrobersb ouersber

I tried to use the following:

myString.replace(/\(.*\)/g,"")

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.

  • What do you mean by escape? Do you mean remove? –  Sep 18 '16 at 15:42
  • When your regexp is not working it's always a good idea to try an on-line regexp tester such as regex101. In addition to testing your regexp it will describe it to you in human terms. In this case, the description for the `*` is: *Quantifier: \* Between zero and unlimited times, as **many times as possible**, giving back as needed [greedy]*. –  Sep 18 '16 at 15:50

2 Answers2

1

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.

Oriol
  • 274,082
  • 63
  • 437
  • 513
0

In addition to Oriol's answer, I see the following possibility. Use [^\)] instead of .: myString.replace(/\([^\)]*\)/g,""). [^\)] matches all characters except for ). [] lists matching characters and ^ at this point inverts them so that all except for the listed ones are matched.

mm759
  • 1,404
  • 1
  • 9
  • 7