简体   繁体   中英

How to replace substrings of a string outside of “”

I have a string like:

'a, b, "c,d" e, f,'

I would like to split my string using the comma character as separator, but outside of the brackets. My result object set should contain the following elements:

a
b
"c,d" e
f

How can I achieve this?

s = 'a, b, "c,d" e, f,';
console.log(s.match(/("[^"]+"|[^,])+/g));

yields [ 'a', ' b', ' "c,d" e', ' f' ] , which has extra spaces, but you can trim them.

Edit: missed the e ... now fixed.

Explanation:

  • (A|B)+ prefers A (which is a quoted string) instead of B, which is a non-quoted part of the string. It matches "c,d" , then because of the + it continues matching e .
  • "[^"]+" matches a " followed by all the non- " , followed by a single " .
  • [^,] matches any non- "
  • /regex/g makes global (matches all matches, not just the first)

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