NIsham Mahsin
NIsham Mahsin

Reputation: 768

Split by new line but skip if it is enclosed within quotes

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

Answers (1)

CertainPerformance
CertainPerformance

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 newlines

Upvotes: 1

Related Questions