Ad

Split A String At The First Two Commas Occuring In Javascript

- 1 answer

Let's consider a variable str defined as :

var str = "A, B, C, D, E, F"

To split the string at comma, I do :

str = str.split(",")
console.log(str)
// => ["A", "B", "C", "D", "E", "F"]

So, what should, I do if I have to split it at the first two commas, such that the output becomes :

// => ["A", "B", "C, D, E, F"]
Ad

Answer

You could split the string, keep the splitting separators and build a new array of parts and joined parts.

function split(string, limit) {
    var parts = string.split(/(,\s*)/),
        result = [],
        i = 0;
    
    while (i < limit * 2) {
        result.push(parts[i]);
        i += 2;
    }
    result.push(parts.slice(limit * 2).join(''));
    return result;
}

console.log(split('A, B, C, D, E, F, G', 2));

Ad
source: stackoverflow.com
Ad