Reputation: 3198
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
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 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 whitespacePS: 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
Upvotes: 4