Code Guy
Code Guy

Reputation: 3198

JS extract all text outside the brackets

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.

Upvotes: 1

Views: 887

Answers (1)

anubhava
anubhava

Reputation: 784958

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

Upvotes: 4

Related Questions