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.
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.
Use method String. split() It returns an array of String, splitted by the character you specified.
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
Here's what I would do.
var str = 'a, b, c, "d, e, f", g, h'; var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
/* 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]);
regex: /,(?=(?:(?:[^"]*"){2})*[^"]*$)/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With