Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Splitting a string by comma but ignoring commas in quotes

I have a string like following

var str="A,B,C,E,'F,G,bb',H,'I9,I8',J,K"

I'd like to split the string on commas. However, in the case where something is inside single quotation marks, I need it to both ignore commas as following.

 A
 B
 C
 E
 F,G,bb
 H
 I9,I8
 J
 K
like image 443
Augustian Joseph Avatar asked May 16 '12 11:05

Augustian Joseph


People also ask

How do you split a string with a comma delimiter?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you split a comma in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.


1 Answers

> str.match(/('[^']+'|[^,]+)/g)
["A", "B", "C", "E", "'F,G,bb'", "H", "'I9,I8'", "J", "K"]

Though you requested this, you may not accounted for corner-cases where for example:

  • 'bob\'s' is a string where ' is escaped
  • a,',c
  • a,,b
  • a,b,
  • ,a,b
  • a,b,'
  • ',a,b
  • ',a,b,c,'

Some of the above are handled correctly by this; others are not. I highly recommend that people use a library that has thought this through, to avoid things such as security vulnerabilities or subtle bugs, now or in the future (if you expand your code, or if other people use it).


Explanation of the RegEx:

  • ('[^']+'|[^,]+) - means match either '[^']+' or [^,]+
  • '[^']+' means quote...one-or-more non-quotes...quote.
  • [^,]+ means one-or-more non-commas

Note: by consuming the quoted string before the unquoted string, we make the parsing of the unquoted string case easier.

like image 153
ninjagecko Avatar answered Nov 14 '22 23:11

ninjagecko