0

I am aware of the fact that, this has been asked before in this forum - Split a string by commas but ignore commas within double-quotes using Javascript. But my requirement is slight different which has been asked here. Sorry for confusing you with my question.

I have a string like below -

myString = " "123","ABC", "ABC,DEF", "GHI" "

Here I want to split this string by comma and store it to an array but ignoring the comma within the double quote. Here is what I have tried so far.

myArray.push(myString.replace(/"/g,"").split(","));

But I'm not sure how to ignore the ',' inside the double quote. Could anyone please help ?

This is how my output should look like -

myArray = ["123","ABC", "ABC,DEF", "GHI"]
chikun
  • 199
  • 1
  • 15

4 Answers4

1

Seems like you already have an array, so there's no comma to split. Converting it .toString() looks like an unnecessary step.

I think you're confusing language syntax with actual data. The double quotes you see aren't part of the content of the strings. It looks like you already have the data you need.

  • Thank you for the reply. I actually made you confused with the input. Actually I want the string to be split with comma. Please see the edits. Apologies for the earlier confusion. – chikun Apr 20 '20 at 16:18
0

One way to do it with the help of split(), map() and replace()

myString = ' "123","ABC", "ABC,DEF", "GHI" ';
console.log(myString.split('",').map(n=>n.replace(/\"| /g,'')));
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

You can try with the regex ([^"])* I did test it on https://regex101.com

This is the result you can see in the image below => https://regex101.com/r/a5dwNY/1

Regex 101 result

Community
  • 1
  • 1
Yak O'Poe
  • 760
  • 4
  • 14
0
myString = ' "123","ABC", "ABC, DEF", "GHI" ';
console.log(JSON.parse(`[${myString}]`));

This should do the trick... Basically what epascarello wrote in the comments to the questions.

Cheers.

Odinn
  • 808
  • 5
  • 23