按新行分割,但如果用引号引起来则跳过

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.

评论
任性
任性

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
点赞
评论