将JavaScript字符串拆分为固定长度的片段 [英] Split a JavaScript string into fixed-length pieces
问题描述
我想将字符串拆分为固定长度(例如 N )。当然,如果原始字符串的长度不是 N 的倍数,则最后一段可能会更短。
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.
我需要最快的方法来执行此操作,而且最简单的写作。我一直这样做的方式如下:
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
我认为必须有更好的方法来做我想要的。但我不想要额外的模块或库,如果可能的话只需要简单的JavaScript。
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.
推荐答案
你可以试试这个:
var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);
这篇关于将JavaScript字符串拆分为固定长度的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!