Javascript: splitting a string with a comma, but ignoring commas in quotes

I have a line like the following

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

I would like to split the string into a comma. However, in the case where something is inside single quotes, I need both to ignore commas, as shown below.

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

Although you requested this, you may not consider corner cases, for example:

  • 'bob\'s'- string in which to 'escape
  • a,',c
  • a,,b
  • a,b,
  • ,a,b
  • a,b,'
  • ',a,b
  • ',a,b,c,'

; - . , , , , , ( ).


RegEx:

  • ('[^']+'|[^,]+) - '[^']+', [^,]+
  • '[^']+' ... ... quote.
  • [^,]+

: , , , .

+12

, . , . . , "\".

var sample='this=that, \
sometext with quoted ",", \
for example, \
another \'with some, quoted text, and more\',\
last,\
but "" "," "asdf,asdf" not "fff\',\'  fff" the least';

var it=sample.match(/([^\"\',]*((\'[^\']*\')*||(\"[^\"]*\")*))+/gm);
for (var x=0;x<it.length;x++) {
var txt=$.trim(it[x]);
if(txt.length)
    console.log(">"+txt+'<');
}​
+6

Use this

            var input="A,B,C,E,'F,G,bb',H,'I9,I8',J,K";
            //Below pattern will not consider comma(,) between ''. So 'I9,I8' will be considered as single string and not spitted by comma(,). 
            var pattern = ",(?=([^\']*\'[^\']*\')*[^\']*$)";
            //you will get acctual output in array
            var output[] = input.split(pattern);
0
source

All Articles