1

I have a string that looks like this

"a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e"

I am trying to split this string by "," and get extract the individual values. Now, what it does is, it splits the part "Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)" also and I get this as the final result

["a", "b", "c", ""Mozilla/5.0", "(compatible;", "MSIE", "9.0;", "Windows", "NT", "6.1;", "Trident/5.0)"", "d", "e"]

Is there a way to make it not split the substring? Basically I am trying to get this after split

["a", "b", "c", "Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)", "d", "e"]
Shanil Arjuna
  • 1,135
  • 10
  • 18
A-D
  • 371
  • 1
  • 9
  • 24
  • Possible duplicate of [How can I parse a CSV string with Javascript, which contains comma in data?](https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data) – user12205 Aug 30 '18 at 06:06

1 Answers1

6

You can use a regular expression, and utilize negative lookahead for non-" characters followed by the ending ",, which would indicate that the current comma is inside a quoted string:

const str = `a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e,"foo,bar,quoted",f,g`;
console.log(str.split(/,(?![^"]+",)/))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320