1

I would like to parse a string like: foo, bar, baz, "hello, world" to output:

["foo", "bar", "baz", "hello, world"]
Trendy
  • 460
  • 2
  • 12
  • 1
    Regex alone is not a great tool for this. Any particular reason you're not [using a library](http://stackoverflow.com/q/1293147/139010), nor using [a non-rubbish format which JS already supports?](http://json.org/) – Matt Ball Jun 25 '14 at 03:16
  • 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) – LWC Sep 21 '17 at 08:35

1 Answers1

5

Just use |

    var regex = /"([^"]*)"|'([^']*)'|[^\s,]+/g;
    var text = "Hello world \"Boston Red Sox\" hello, world, \'boston, red sox\', \'beached whale\', pickup sticks";
    var output = [];
    var m;
    while ((m = regex.exec(text)) !== null)
    {
        output.push(m[1] || m[2] || m[0]);
    }
    console.log(output);

fiddle

LWC
  • 1,084
  • 1
  • 10
  • 28
Fabricator
  • 12,722
  • 2
  • 27
  • 40