将JavaScript字符串拆分为固定长度的片段

时间:2021-07-14 03:14:26

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.

我想将一个字符串拆分成固定长度(例如N个)。当然,如果原始字符串的长度不是N的倍数,则最后一块可能更短。

I need the fastest method to do it, but also the simplest to write. The way I have been doing it until now is the following:

我需要最快的方法来完成它,但也是最简单的方法。我一直这样做的方式如下:

var a = 'aaaabbbbccccee';
var b = [];
for(var i = 4; i < a.length; i += 4){ // length 4, for example
    b.push(a.slice(i-4, i));
}
b.push(a.slice(a.length - (4 - a.length % 4))); // last fragment

I think there must be a better way to do what I want. But I don't want extra modules or libraries, just simple JavaScript if it's possible.

我认为必须有更好的方法来做我想做的事情。但我不想要额外的模块或库,只要简单的JavaScript就可以。

Before ask, I have seen some solutions to resolve this problem using other languages, but they are not designed with JavaScript in mind.

在问之前,我已经看到了一些使用其他语言解决这个问题的解决方案,但它们并没有考虑到JavaScript的设计。

2 个解决方案

#1


18  

You can try this:

你可以试试这个:

var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);

#2


4  

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

请参阅此相关问题:https://*.com/a/10456644/711085和https://*.com/a/8495740/711085(如果性能有问题,请参阅评论中的性能测试。)

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"]

#1


18  

You can try this:

你可以试试这个:

var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);

#2


4  

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

请参阅此相关问题:https://*.com/a/10456644/711085和https://*.com/a/8495740/711085(如果性能有问题,请参阅评论中的性能测试。)

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"]