简体   繁体   中英

Split the string using comma but ignore the comma within double quotes - javascript

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

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.

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

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

正则表达式 101 结果

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM