Js如何快速切割字符串

RT,有这么一个字符串

 var mStr = 'total:week7:30;week6:30;week5:30;week4:30;week3:30;week2:30;week1:30;;count:week7:5;week6:2;week5:1;week4:3;week3:5;week2:4;week1:3;'

目标是切割成两个数组

 total =  ["30", "30", "30", "30", "30", "30", "30"]
 count = ["3", "4", "5", "3", "1", "2", "5"]

我自己的方法是这样的

 function splitStr(e) {
    var i = 0, j = 0
    var mData1 = e.split(';')
    var mData2 = new Array()
    for (i = 0; i < mData1.length; i++) {
        mData2[i] = mData1[i].split(':')
    }
    var mArray1 = new Array()
    var mArray2 = new Array()
    var k = 0
    for (i = 0; i < 7; i++) {
        k = 0
        for (j = 0; j < mData2.length; j++) {
            var checkStr = 'week' + (i + 1)

            if (mData2[j][0].indexOf(checkStr) != -1) {
                if (k == 0) {
                    mArray1[i] = mData2[j][1]
                    k = 1
                }
                else {
                    mArray2[i] = mData2[j][1]
                }
            }
        }
    }
    for(i = 0; i < 7; i++){
        if(isNaN(mArray1[i])){
            mArray1[i] = 0
        }
        if(isNaN(mArray2[i])){
            mArray2[i] = 0
        }
    }
    console.log(mArray1)
    console.log(mArray2)
}

我的问题就是有没有更加快速的方法来进行切割,或者对这个方法进行优化

2个回答


    var mStr = 'total:week7:30;week6:30;week5:30;week4:30;week3:30;week2:30;week1:30;;count:week7:5;week6:2;week5:1;week4:3;week3:5;week2:4;week1:3;'
    mStr = mStr.split('count:');
    var total = mStr[0].match(/(\d+)(?=;)/g);
    alert(total)
    var count = mStr[1].match(/(\d+)(?=;)/g);
    alert(count)
Tim18318741662
无奈白了少年头 回复showbo: 好的,谢谢大神
接近 3 年之前 回复
showbo
支付宝加好友偷能量挖 回复无奈白了少年头: 自己修改正则匹配week7:30,然后变量分组做你的处理。
接近 3 年之前 回复
Tim18318741662
无奈白了少年头 如果想一个判断,判断其中某个week缺失,输出的数组中该week对应的数据就变成0呢,也可以用正则表达式吗,谢谢大神
接近 3 年之前 回复

正则表达式,功能好强大。。。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问