Split a JavaScript string into fixed-length pieces

前端 未结 2 1704
再見小時候
再見小時候 2021-02-07 09:03

I would like to split a string into fixed-length (N, for example) pieces. Of course, last piece could be shorter, if original string\'s length is not multiple of N<

相关标签:
2条回答
  • 2021-02-07 09:39

    See this related question: https://stackoverflow.com/a/10456644/711085 and https://stackoverflow.com/a/8495740/711085 (See performance test in comments if performance is an issue.)

    First (slower) link:

    [].concat.apply([],
        a.split('').map(function(x,i){ return i%4 ? [] : a.slice(i,i+4) })
    )
    

    As a string prototype:

    String.prototype.chunk = function(size) {
        return [].concat.apply([],
            this.split('').map(function(x,i){ return i%size ? [] : this.slice(i,i+size) }, this)
        )
    }
    

    Demo:

    > '123412341234123412'.chunk(4)
    ["1234", "1234", "1234", "1234", "12"]
    
    0 讨论(0)
  • 2021-02-07 09:44

    You can try this:

    var a = 'aaaabbbbccccee';
    var b = a.match(/(.{1,4})/g);
    
    0 讨论(0)
提交回复
热议问题