1

I have the following string:

'"alpha", "beta", "gamma", "delta"'

How can I convert the string into an array such that:

array = ["alpha", "beta", "gamma", "delta"];

So I can call on individual elements of the array such that:

array[0] = "alpha"

I've attempted using str.split but am unsure of the correct usage to separate the quotation marks and commas.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Saeed Ludeen
  • 368
  • 3
  • 11
  • Does this answer your question: https://stackoverflow.com/questions/2858121/convert-comma-separated-string-to-array – Cale Sweeney Oct 10 '17 at 23:14
  • Where did you get that string? Is its format defined somewhere? – Ry- Oct 10 '17 at 23:15
  • @CaleSweeney That's the thread I've been looking at but haven't been able to get it to work with the quotation marks, spaces and commas. – Saeed Ludeen Oct 10 '17 at 23:15
  • @ScottMarcus I edited the original post to clarify. This is the result using cors-anywhere to pull a variable from another website. The string of variables is truncated from the pulled data. – Saeed Ludeen Oct 10 '17 at 23:17
  • @SaeedLudeen: Which website? Is it actually JSON or something? – Ry- Oct 10 '17 at 23:18
  • @Ryan Yes. It's not a homework assignment. I've got a website with an array stored correctly as array = ["alpha, "beta", "gamma"] I've made a JSON request but this pulls the whole webpage as a single string. I then truncated this to just "alpha, "beta", "gamma" but it remains a string of text. I want to be able to convert this back into an array. – Saeed Ludeen Oct 10 '17 at 23:21
  • 2
    @SaeedLudeen: Don’t chop the brackets off. It’ll probably be valid JSON then. (No guarantees when you’re parsing JavaScript without a JavaScript parser, though.) – Ry- Oct 10 '17 at 23:37

4 Answers4

2

Modify the string so that it's valid JSON, then JSON.parse() it:

var str = '"alpha", "beta", "gamma", "delta"';
var json = '[' + str + ']';
var array = JSON.parse(json);

console.log(array[0])
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
2

This will do the trick for you:

str.replace(/\"/g, '').split(', ')

Neil Girardi
  • 4,533
  • 1
  • 28
  • 45
  • 1
    This answer's behavior differs from the accepted answer. If one of the strings contain a comma, then the string is split into two entries with this approach, e.g. `"alpha, beta", "gamma"` becomes `["alpha, beta", "gamma"]` with the accepted answer, and `["alpha", "beta", "gamma"]` with this answer. – Patrick Roberts Jan 07 '19 at 23:24
1

Remove the quotations and spaces, then split on the comma

var str = '"alpha", "beta", "gamma", "delta"';
var strArray = str.replace(/"/g, '').replace(/ /g, '').split(',');
ryan
  • 1,451
  • 11
  • 27
1

Possibly more efficient than the others; trim off the 1st and last " characters and split on the ", " sequence.

var str = '"alpha", "beta", "gamma", "delta"';
var str2 = str.substr(1, str.length - 2).split('", "');
console.log(str2);
Gershom Maes
  • 7,358
  • 2
  • 35
  • 55