split string in two on given index and return both parts

前端 未结 8 2162
攒了一身酷
攒了一身酷 2020-12-05 12:33

I have a string that I need to split on a given index and then return both parts, seperated by a comma. For example:

string: 8211 = 8,211
        98700 = 98,         


        
8条回答
  •  感情败类
    2020-12-05 12:59

    You can also do it like this.
    https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp

    var str, result;
    str = prompt("Enter Any Number");
    
    var valueSplit = function (value, length) {
        if (length < 7) {
            var index = length - 3;
            return str.slice(0, index) + ',' + str.slice(index);
        }
        else if (length < 10 && length > 6) {
            var index1, index2;
            index1 = length - 6;
            index2 = length - 3;
            return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);
        }
    }
    
    result = valueSplit(str, str.length);
    alert(result);
    

提交回复
热议问题