I'm trying to split a string that contains consecutive commas as well as a comma wrapped in quotation marks but can't quite get the result that I want. Here is an example of a string I have:
var str = ‘10,Apple,"Sweet Gala apple, from Australia",,,,,,in stock,3.99’
where the third element has a comma inside quotation marks, followed by multiple commas.
I want to split the string by commas under two conditions: 1) don't split the comma that's wrapped inside quotations marks 2) between the multiple commas that are next to each other should be treated as a blank space
When I use the regex below:
str.match(/(".*?"|[^,]+)/g)
The result comes out to the array below which meets the first condition but fails to insert a blank space between the consecutive commas
["10","Apple",""Sweet Gala apple, from Australia"","in stock","3.99"]
I want it to look like:
["10","Apple",""Sweet Gala apple, from Australia"",'','','','','',"in stock","3.99"]
What do I need to do to meet the above two conditions?