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.

7
  • Does this answer your question: stackoverflow.com/questions/2858121/… Commented Oct 10, 2017 at 23:14
  • Where did you get that string? Is its format defined somewhere? Commented Oct 10, 2017 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. Commented Oct 10, 2017 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. Commented Oct 10, 2017 at 23:17
  • 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.) Commented Oct 10, 2017 at 23:37

4 Answers 4

1

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])

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work when string is already inside another JSON object.
@EdgarQuintero not really sure what you're saying... "inside a JSON object"??
1

This will do the trick for you:

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

1 Comment

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.
0

Remove the quotations and spaces, then split on the comma

var str = '"alpha", "beta", "gamma", "delta"';
var strArray = str.replace(/"/g, '').replace(/ /g, '').split(',');

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.