Split an array into new character limit arrays in each array

Asked

Viewed 555 times

1

My problem is this:

I have the input string: "A|BB|CCC|DDDD|EEEEE|FFFFFF|GGGGGGG". I need to split this string in "|", so that in the case divided into 6.

But I need each value to enter an array of no more than 10 characters and with the "|".

For example:

array(0) = "A|BB|CCC" //8 caracteres

array(1) = "DDDD|EEEEE" //10 caracteres

array(2) = "FFFFFF" //6 caracteres

array(3) = "GGGGGGG" //7 caracteres

Like I’ve done so far:

  • I used the split to break the input string;
  • I made a for in the size of the array formed by the split;
  • I run each array value next to a counter in an if that puts the values concatenated with "|" inside the array.

1 answer

1

I managed to do with the function dividePartes below. Click the blue button Execute to test:

function dividePartes(s) {
    var partes = s.split("|");
    var resultado = [];
    var pedaco = "";

    for (var i = 0; i < partes.length; i++) {
        var adicionando = pedaco;
        if (adicionando === "") {
            adicionando = partes[i];
        } else {
            adicionando += "|" + partes[i];
        }
        if (adicionando.length <= 10) {
            pedaco = adicionando;
        } else {
            resultado.push(pedaco);
            pedaco = partes[i];
        }
    }
    resultado.push(pedaco);
    return resultado;
}

var a = "A|BB|CCC|DDDD|EEEEE|FFFFFF|GGGGGGG";
document.write(JSON.stringify(dividePartes(a)));

var b = "A|BB|CCC|DDDD|EE|FFF|GG|HH|I|J|KKKKKKKKKKKK|LL|MM|NN";
document.write(JSON.stringify(dividePartes(b)));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.