JavaScript/jQuery: Split a Text up to Occurence of a Symbol Using Loop

I have a text content as follows:

var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^..."

I want to split the text up-to multiple of 5th occurrence of ^ and pass to a function with the ^ symbol.

If there are 31 ^ in the element then: 5th, 10th, 15th, 20th, 25th, 30th and then remaining should be passed to the function (i.e. 31st with ^).

I prefer a for loop like:

var spl = text.split(); //up-to 5th multiple

for(i=0; i<spl.length; i++){
 passfun(upto 5th^ with cap symbol)
}

Example:

var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^sssad^gsds..."

passfun("asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^"); //1st time
passfun("dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^");//2nd time
passfun("sssad^gsds");//last

Answers 1

  • Hello friend it perfect little bit may be length correction need if you have any problem then otherwise no need

    var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^split^text^upto^5th^and^..";
                    //I want to split the text upto multiple of 5th occurrance of ^ and
                    //var abc =  text.split("^").length - 1;
                    var counter = 0, index = 0;
                    var temp = 0, indexArr = [];
                    for (var i = 0; i < text.length; i++) {
                        index++;
                        if (text.charAt(i) == '^') {
                            counter++;
                        }
                        if (counter == 5) {
                            counter = 0;
                            myString(index);
                        }
                    }
                    function myString(tempindex) {
                        var tempString = '';
                        indexArr[temp] = tempindex;
                        if (temp == 0) {
                            tempString = text.substr(0, tempindex);
                            passfun(tempString);
                            temp++;
                        } else {
                            tempString = text.substr(indexArr[temp - 1], indexArr[temp - 1]);
                            passfun(tempString);
                            temp++;
                        }
                        return;
                    }
    

Related Articles