split string in two on given index and return both parts

前端 未结 8 2146
攒了一身酷
攒了一身酷 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:55

    If code elegance ranks higher than the performance hit of regex, then

    '1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
    => "1234,567"
    

    There's a lot of room to further modify the regex to be more precise.

    If join() doesn't work then you might need to use map with a closure, at which point the other answers here may be less bytes and line noise.

    0 讨论(0)
  • 2020-12-05 12:58

    You can also use number formatter JS available at

    https://code.google.com/p/javascript-number-formatter/

    Format options

    http://jsfiddle.net/chauhangs/hUE3h/

      format("##,###.", 98700)
      format("#,###.", 8211)
    
    0 讨论(0)
  • 2020-12-05 12:59

    ES6 1-liner

    // :: splitAt = number => Array<any>|string => Array<Array<any>|string>
    const splitAt = index => x => [x.slice(0, index), x.slice(index)]
    
    console.log(
      splitAt(1)('foo'), // ["f", "oo"]
      splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]
    )
      

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-05 13:01

    Try this

    function split_at_index(value, index)
    {
     return value.substring(0, index) + "," + value.substring(index);
    }
    
    console.log(split_at_index('3123124', 2));

    0 讨论(0)
  • 2020-12-05 13:07

    You can easily expand it to split on multiple indexes, and to take an array or string

    const splitOn = (slicable, ...indices) =>
      [0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));
    
    splitOn('foo', 1);
    // ["f", "oo"]
    
    splitOn([1, 2, 3, 4], 2);
    // [[1, 2], [3, 4]]
    
    splitOn('fooBAr', 1, 4);
    //  ["f", "ooB", "Ar"]
    

    lodash issue tracker: https://github.com/lodash/lodash/issues/3014

    0 讨论(0)
提交回复
热议问题