Example string:
"Foo","Bar, baz","Lorem","Ipsum"
Here we have 4 values in quotes separated by commas.
When I do this:
str.split(',').forEach(…
than that will also split the value "Bar, baz"
which I don't want. Is it possible to ignore commas inside quotes with a regular expression?
One way would be using a Positive Lookahead assertion here.
var str = '"Foo","Bar, baz","Lorem","Ipsum"',
res = str.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
Regular expression:
, ','
(?= look ahead to see if there is:
(?: group, but do not capture (0 or more times):
(?: group, but do not capture (2 times):
[^"]* any character except: '"' (0 or more times)
" '"'
){2} end of grouping
)* end of grouping
[^"]* any character except: '"' (0 or more times)
$ before an optional \n, and the end of the string
) end of look-ahead
Or a Negative Lookahead
var str = '"Foo","Bar, baz","Lorem","Ipsum"',
res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With