-3

I have this string

var string = 'foo , bar , "special1,special2,special3" , "random1,random2" , normal , another item'

I want to split this on , and keep the things within quotes as is in the array i.e i do not want to split the string within quotes. So the expected output would be

var array = ['foo', 'bar', 'special1,special2,special3', 'random1,random2', 'normal', 'another item']
Anubhav
  • 7,138
  • 5
  • 21
  • 33

1 Answers1

2

You can split the string by the , separator and then remove the double-quotes from any element of array.

var string = 'foo , bar , "special1,special2,special3" , "random1,random2" , normal , another item';

var array = string.split(' , ').map(function(x) {
  return x.replace(/"/g, "")
});

alert(JSON.stringify(array));
nicael
  • 18,550
  • 13
  • 57
  • 90
void
  • 36,090
  • 8
  • 62
  • 107