Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by commas but ignore commas within double-quotes using Javascript

I'm looking for [a, b, c, "d, e, f", g, h]to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm trying to do this through Javascript. This is what I have so far:

str = str.split(/,+|"[^"]+"/g);  

But right now it's splitting out everything that's in the double-quotes, which is incorrect.

Edit: Okay sorry I worded this question really poorly. I'm being given a string not an array.

var str = 'a, b, c, "d, e, f", g, h'; 

And I want to turn that into an array using something like the "split" function.

like image 765
jpecht Avatar asked Jul 12 '12 16:07

jpecht


People also ask

How do you split a comma in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

How do you separate a string split by a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);


2 Answers

Here's what I would do.

var str = 'a, b, c, "d, e, f", g, h'; var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g); 

enter image description here /* will match:

    (         ".*?"       double quotes + anything but double quotes + double quotes         |           OR         [^",\s]+    1 or more characters excl. double quotes, comma or spaces of any kind     )     (?=             FOLLOWED BY         \s*,        0 or more empty spaces and a comma         |           OR         \s*$        0 or more empty spaces and nothing else (end of string)     )      */ arr = arr || []; // this will prevent JS from throwing an error in // the below loop when there are no matches for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]); 
like image 137
inhan Avatar answered Oct 04 '22 13:10

inhan


regex: /,(?=(?:(?:[^"]*"){2})*[^"]*$)/

enter image description here

const input_line = '"2C95699FFC68","201 S BOULEVARDRICHMOND, VA 23220","8299600062754882","2018-09-23"'  let my_split = input_line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)[4]  Output:  my_split[0]: "2C95699FFC68",  my_split[1]: "201 S BOULEVARDRICHMOND, VA 23220",  my_split[2]: "8299600062754882",  my_split[3]: "2018-09-23" 

Reference following link for an explanation: regexr.com/44u6o

like image 24
f-society Avatar answered Oct 04 '22 14:10

f-society