将字符串拆分为等长字符串的数组

时间:2020-12-11 21:38:34

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

1 个解决方案

#1


59  

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.

将匹配与全局标志结合使用,而不是拆分。需要{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

#1


59  

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.

将匹配与全局标志结合使用,而不是拆分。需要{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