atc
atc

Reputation: 621

split by comma inside a string using javascript

I have a string like this

var str = "n,m,'klj,klp',ml,io"; // not the quotes arround klj,klp

I use javascripts .split() but it returns like this

n
m
klj
klp
ml
io

But I need it as below,not getting any idea

n
m
klj,klp
ml
io

Upvotes: 2

Views: 555

Answers (5)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

You can use Array.prototype.split() method with regex for this.

var str = "n,m,'klj,klp',nl,'klj,x,y,klp','klj,klp',ml,io";
var splits = str.split(/'([^']+)'|([^,]+)/);
var results = splits.filter(function(v){
    if (v && v!== ",")
        return true;
    return false;
});

document.write("<br>Output: " + JSON.stringify(results));

Upvotes: 0

embearr
embearr

Reputation: 1

C-like solution

function em_split(str) {
    var ret = [], p0 = 0, p1 = 0, p2 = 0, pe = 0;
    while ((p1 = str.indexOf(",",pe)) != -1) {
        if ((p2 = str.indexOf("'",pe)) != -1 ) {
            if (p2 < p1) {
                if (p2==pe) {
                    pe = ((p2 = str.indexOf("'",p1)) == -1) ? p1 : p2;
                } else pe = p1;
            } else pe = p1;
        } else { pe = p1; }
        ret.push(str.substr(p0,pe-p0));
        pe = (pe == p2) ? pe+2 : pe+1;
        p0 = pe;
    }
    ret.push(str.substr(p0,str.length));
    return ret;
}

example use:

console.log(em_split("n,m,'klj,klp',ml,io"));
console.log(em_split("n,m,'klj,klp,ml,io"));
console.log(em_split("n,m,klj,klp',ml,io"));

will return:

Array [ "n", "m", "'klj,klp", "ml", "io" ]
Array [ "n", "m", "'klj", "klp", "ml", "io" ]
Array [ "n", "m", "klj", "klp'", "ml", "io" ]

Upvotes: 0

atc
atc

Reputation: 621

If anyone wants to not hardcode values AS I have done,there is another way then only above match....map function work

add this incase you are refering from selectbox,textbox etc...

var newValue = $(".client option:selected").text();

      if (/,/i.test(newValue)) {
         newValue = "'" + newValue + "'";
     }
newValue.match( /'[^']+'|[^,]+/g ).
    map( function( x ) { return x.replace( /^'|'$/g, '' ) } );

Upvotes: 0

Neelabh
Neelabh

Reputation: 446

Another solution:

var splitStrings = (function () {
  var regex = /'.*?'/g;

  return function (str) {
    var results = [], matches;
    matches = str.match(regex);
    if (matches) {
      results = matches.map(function (match) {
        return match.substring(1, match.length-1);
      });
    }
    return results.concat(str.replace(regex, '').split(',').filter(function (s) {
      return s !== '';
    }));
  };
})();

It is a function wrapped inside a closure to keep the regex private.

console.log(splitStrings("n,m,'klj,klp',ml,io"));
// prints ["klj,klp", "n", "m", "ml", "io"]

The example from Zsolt's answer:

console.log(splitStrings("n,m,'klj,klp',ml,io,'test,test,a,b','test',test"));
// prints ["klj,klp", "test,test,a,b", "test", "n", "m", "ml", "io", "test"]

Note that the function doesn't preserve the order of strings.

Upvotes: 0

Ugly, simple:

"n,m,'klj,klp',ml,io,'test,test,a,b','test',test".
    match( /'[^']+'|[^,]+/g ).
    map( function( x ) { return x.replace( /^'|'$/g, '' ) } );

Result:

["n", "m", "klj,klp", "ml", "io", "test,test,a,b", "test", "test"]

If this sample is from a CSV file, you have to look out for more gotchas.

Upvotes: 2

Related Questions