-1

I need to convert this string:

'"apple","banana","yellow peach","orange"'

to an array:

["apple","banana","yellow peach","orange"]
  • 2
    Possible duplicate of [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java). This is a simple variation. `string.split(',')` gives an array of strings with quotes. `array.map()` the result to remove the quotes – Tibrogargan Aug 16 '16 at 22:56
  • 2
    `JSON.parse("[" + my_string + "]")` –  Aug 16 '16 at 23:00
  • @Tibrogargan this is for JavaScript, not Java. – Tyler at Maijlet Aug 17 '16 at 04:06
  • 1
    Can the quotes strings contain commas? –  Aug 17 '16 at 04:58

1 Answers1

1

Edit:

Squint's solution using JSON.parse() is fine for this example, however, if there are nested quotation marks within your string, JSON.parse() will error. For example:

var str = '"apple","banana","yellow peach","orange", "Dwayne "The Rock" Johnson"';

You will have to be aware of what your data could potentially look like. There may be instances where the inner quotations are needed and so you can't use a global replace of the quotation marks nor JSON.parse(), and you would need to do something like this:

var str = '"apple","banana","yellow peach","orange", "Dwayne "The Rock" Johnson"';
var arr = str.split(",").map(function (elem) {
  return elem.trim().replace(/^"|"$/g, ''); // regex courtesy of torazaburo =)
});
console.log(arr);
mhodges
  • 10,938
  • 2
  • 28
  • 46
  • 2
    Globally replacing quotes is heavy handed and may be incorrect depending on the data. – Tibrogargan Aug 16 '16 at 23:01
  • 2
    @Tibrogargan Agreed, this works for this OP's request, but is a limited case solution - squint's comment is a better solution. Although now that I think about it, the JSON.parse() solution will break if you have any nested quotations inside of the original string.. pick your poison – mhodges Aug 16 '16 at 23:07
  • 2
    Better to split first, and then just remove leading and trailing quotes with `replace(/^"|"$/g, '')`. –  Aug 17 '16 at 04:57
  • @torazaburo Completely forgot about the ^$ in regex. Durp. haha thank you! – mhodges Aug 17 '16 at 15:41
  • Your code does not work, I put it into a snippet. Please check. – Wiktor Stribiżew Aug 18 '16 at 21:34
  • @WiktorStribiżew Yeahhhh that was me not paying attention, good catch! Thank you. I have updated it so it works now. – mhodges Aug 18 '16 at 23:20
  • Now, the only trouble is potential presence of commas inside values. – Wiktor Stribiżew Aug 19 '16 at 06:00
  • @WiktorStribiżew Yeah, and that will be left as an exercise for the reader ;) – mhodges Aug 19 '16 at 15:18