0

I have a string like this:

"foo", "bar", "baz"

I want, with a regex, get the single string;

["foo", "bar", "baz"]

This is my code:

var re = new RegExp('"(?:[^"])*"', 'g');
var match = re.exec('"foo", "bar", "baz"');
console.log(match);

but doesn't check for the separator , and return only foo...

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
ar099968
  • 6,963
  • 12
  • 64
  • 127

3 Answers3

0

You can choose to use split(/,\s+/) and replace() for that output:

var str = '"foo", "bar", "baz"';
var res = str.split(/,\s+/).map(item=>item.replace(/"/g, ''));
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You could add brackets and parse the JSON.

var string = '"foo", "bar", "baz"',
    array = JSON.parse('[' + string + ']');
    
console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here's a solution that chops off the leading/trailing quotes and splits on the delimiter:

const s = '"foo", "bar", "baz"';
console.log(s.slice(1, s.length-1).split('", "'));
ggorlen
  • 44,755
  • 7
  • 76
  • 106