Is there a javascript/jquery method or function that will let me split a string at nth occurrence of a selected delimiter? I'd like it work just like the regular str.split(delimiter) except instead of splitting at every occurrence of the delimiter it could be instructed to skip n number of them each time.
var str = "A,BB,C,DDD,EEEE,F";
var strAry = str.split(",");
Would result in strAry looking like {"A","BB","C","DDD","EEEE","F"}
What I want would be {"A,BB","C,DDD","EEEE,F"} assuming I set nth occurance to 2.
I wrote a small function that appears to work but hoping there was a simpler way to do this:
function splitn(fullString, delimiter, n){
var fullArray = fullString.split(delimiter);
var newArray = [];
var elementStr = "";
for(var i = 0; i < fullArray.length; i++) {
if (i == fullArray.length-1) {
if (elementStr.length == 0) {
elementStr = fullArray[i];
} else {
elementStr += (delimiter + fullArray[i]);
}
newArray.push(elementStr);
} else {
if (((i + 1) % n) == 0) {
if (elementStr.length == 0) {
elementStr = fullArray[i];
} else {
elementStr += (delimiter + fullArray[i]);
}
newArray.push(elementStr);
elementStr = "";
} else {
if (elementStr.length == 0) {
elementStr = fullArray[i];
} else {
elementStr += (delimiter + fullArray[i]);
}
}
}
};
return newArray;
};
Thanks.