将 JavaScript 字符串拆分为固定长度的片段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10474992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a JavaScript string into fixed-length pieces
提问by sgmonda
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。
回答by Danilo Valente
You can try this:
你可以试试这个:
var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);
回答by ninjagecko
See this related question: https://stackoverflow.com/a/10456644/711085and https://stackoverflow.com/a/8495740/711085(See performance test in comments if performance is an issue.)
请参阅此相关问题:https: //stackoverflow.com/a/10456644/711085和https://stackoverflow.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"]