Reputation: 768
I have some strings separated by new line(\n
) and i want to split by \n
i am doing like this
const str = 'ab\ncd\nef\n"g\nh"'
const array = str.split('\n');
But this is also splitting \n
within quotes. how can i skip the \n within quotes.
Upvotes: 0
Views: 133
Reputation: 371138
You can use match
instead: either match match quotes eventually followed by another quote, or match any characters but newlines:
const str = 'ab\ncd\nef\n"g\nh"';
const arr = str.match(/"[^"]*"|.+/g);
console.log(arr);
"[^"]*"
- Match a "
, eventually followed by another `".+
- Match anything but newlinesUpvotes: 1