Reputation: 1877
I have following string and want to match string which are not in bracket"()".
i have tried it with following but it give match with bracket and i want to its inverse.
var str = '45.6 fl oz (456 g)';
console.log(str.match(/[\(]+[^\)]*\)/g));
Can any one help me? I want to following output:-
45.6 fl oz
(456 g)
Upvotes: 1
Views: 1436
Reputation: 626689
You may split with /\s*(\([^()]*\))/
:
var str = '45.6 fl oz (456 g)';
console.log(str.split(/\s*(\([^()]*\))/).filter(Boolean));
//Or, split with whitespaces before a (:
console.log(str.split(/\s*(?=\()/));
The pattern matches
\s*
- 0+ whitespace chars(\([^()]*\))
- Capturing group #1 (its value will be part of the resulting array):
\(
- a (
[^()]*
- any 0+ chars other than (
and )
\)
- a )
.To exclude (
and )
in the result, adjust the capturing group boundaries: /\s*\(([^()]*)\)/
.
The .filter(Boolean)
will remove redundant leading/trailing empty array items that appear when the match is found at the start/end of the string.
The second variant, /\s*(?=\()/
, just matches 0+ whitespace chars that are immediatley followed with a (
char (thanks to the (?=\()
lookahead).
Upvotes: 2
Reputation: 23859
You need to capture two groups essentially; one, which targets the text not in ()
and another, which targets the text in ()
:
var str = '45.6 fl oz (456 g)';
console.log(str.match(/([^()])+|(\(.*\))/g).map(item => item.trim()));
Upvotes: 3