1

I need to extract the text outside the square/round brackets.

"WALL COLOR (IS HERE) [SHERWIN-WILLIAMS]"

The expected result is "WALL COLOR" and not "WALL COLOR "

I have tried with

"WALL COLOR (IS HERE) [SHERWIN-WILLIAMS]".match(/\[(.*?)\]/)[0]

Whether a [0] is needed to get result as string instead array.

anubhava
  • 761,203
  • 64
  • 569
  • 643
Code Guy
  • 3,059
  • 2
  • 30
  • 74

1 Answers1

3

Assuming your brackets are balanced and there is no escaping etc, It will be easier to do it via .replace. You may use this .replace method to remove all strings that are [...] and (...) surrounded with optional whitespaces on both sides.

str = str.replace( /\s*(?:\[[^\]]*\]|\([^)]*\))\s*/g, "" )
//=> "WALL COLOR"

RegEx Demo

RegEx Details:

  • \s*: Match 0 or more whitespace
  • (?:: Start non-capturing group
    • \[[^\]]*\]: Match text that is [...]
    • |: OR
    • \([^)]*\): Match text that is (...)
  • ): End non-capturing group
  • \s*: Match 0 or more whitespace

PS: If you want to allow escaped brackets in your input i.e. WALL COLOR (IS \(escaped\) HERE) [SHERWIN-\[WILL\]IAMS] then use this bit more complex regex:

/\s*(?:\[[^\\\]]*(?:\\.[^\\\]]*)*\]|\([^\\)]*(?:\\.[^\\)]*)*\))\s*/g

RegEx Demo 2

anubhava
  • 761,203
  • 64
  • 569
  • 643