简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM