【问题标题】:JavaScript/jQuery: Split a Text up to Occurence of a Symbol Using LoopJavaScript/jQuery:使用循环将文本拆分为符号的出现
【发布时间】:2016-04-06 04:36:41
【问题描述】:

我有一段文字内容如下:

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

我想将文本拆分为 ^ 第 5 次出现的倍数,并传递给带有 ^ 符号的函数。

如果元素中有 31 个 ^,则:第 5、10、15、20、25、30 和剩余的应该传递给函数(即 31 和 ^)。

我更喜欢 for 循环,例如:

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

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

例子:

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

【问题讨论】:

  • 我会在每个 '^' 上拆分,然后在 for 循环中将 5 个字符串添加到一行。
  • @Poul Bak 你能做个小提琴吗?

标签: javascript jquery split


【解决方案1】:

试试这样的

var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf^...";
var spl = text.split('^');
Array.prototype.chunk = function ( n ) {
    if ( !this.length ) {
        return [];
    }
    return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
console.log(spl.chunk(5)[0].join('^')+'^');

更多信息 Split array into chunks

在这里演示: https://jsfiddle.net/bo4eacv5/1/

【讨论】:

  • 你把最后的+'^'去掉
【解决方案2】:

你可以试试这个:

var text = "asd^dfdf^dsfgdsfg^zdfsd^sdfsdf^dfsdf^dsfsdf^dfsdf^dfsf^sdfsdf",
    temp = text.split('^');
for (i = 0; i < temp.length; i += 5) {
  passfun(temp.slice(i, 5 + i).join('^') + ( i + 5 < temp.length ? '^' : ''));
}

【讨论】:

【解决方案3】:

你好朋友,如果你有任何问题,它完美的一点可能是长度校正,否则不需要

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;
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多