Filip Lauc
Filip Lauc

Reputation: 3029

Split by RegExp

I need to find a way to split this string based on comma ','.

"saleHours.sunTo(saleHours.satTo, saleHours.satFrom), saleHours.funTest(saleHours.sunFrom)"

However this is the desired result:

["saleHours.sunTo(saleHours.satTo, saleHours.satFrom)", saleHours.funTest(saleHours.sunFrom)"]

Not this:

["saleHours.sunTo(saleHours.satTo", " saleHours.satFrom)", " saleHours.funTest(saleHours.sunFrom)"].

So I somehow need to escape the commas within '()'.

Any help is greatly appreciated, thank you.

Upvotes: 2

Views: 66

Answers (2)

ZiTAL
ZiTAL

Reputation: 3581

var input = "saleHours.sunTo(saleHours.satTo, saleHours.satFrom), saleHours.funTest(saleHours.sunFrom)";

    var m = input.split(/\),/);
    var l = m.length;
    for(i in m)
    {
        if(i<l-1)
            m[i] = m[i]+")";
    }

    console.log(m);

output:

[ 'saleHours.sunTo(saleHours.satTo, saleHours.satFrom)',
  ' saleHours.funTest(saleHours.sunFrom)' ]

Upvotes: 3

Ricardo Morais
Ricardo Morais

Reputation: 26

Not sure if you have any other requirements but this code splits the string in the last comma:

str.split(/[\s,]+/)

Upvotes: -1

Related Questions