javascript 将字符串拆分为等长字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8359905/
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 string into array of equal length strings
提问by trumank
I have a string that I need split into smaller strings with an equal length of 6. I tried using:
我有一个字符串,我需要将其拆分为长度为 6 的较小字符串。我尝试使用:
'abcdefghijklmnopqrstuvwxyz'.split(/(.{6})/)
But it returns an array with empty strings like so:
但它返回一个包含空字符串的数组,如下所示:
["", "abcdef", "", "ghijkl", "", "mnopqr", "", "stuvwx", ""]
回答by Rob W
Use match
in conjunction with a global flag, instead of split. {1,6}
is needed, to also include the last part of the matched string. Patterns are greedy by default, which means that as much is matched as possible. So, .{1,6}
will only match less than 6 characters at the end of a string.
使用match
与全球标志一起,而不是分裂。{1,6}
需要,还包括匹配字符串的最后一部分。默认情况下,模式是贪婪的,这意味着尽可能多地匹配。因此,.{1,6}
只会匹配字符串末尾的少于 6 个字符。
'abcdefghijklmnopqrstuvwxyz'.match(/.{1,6}/g);
Result:
结果:
["abcdef", "ghijkl", "mnopqr", "stuvwx", "yz"];
Note that the returned object is a true array. To verify:
请注意,返回的对象是一个真正的数组。验证:
console.log('.'.match(/./g) instanceof Array); //true