将字符串拆分为等长字符串的数组 [英] Split string into array of equal length strings
本文介绍了将字符串拆分为等长字符串的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,我需要拆分成较小的字符串,长度相等6.我尝试使用:
I have a string that I need split into smaller strings with an equal length of 6. I tried using:
'abcdefghijklmnopqrstuvwxyz'.split(/(.{6})/)
但它返回一个空的数组像这样的字符串:
But it returns an array with empty strings like so:
["", "abcdef", "", "ghijkl", "", "mnopqr", "", "stuvwx", ""]
推荐答案
使用匹配
与全局标志匹配,而不是拆分。需要 {1,6}
,以包括匹配字符串的最后一部分。默认情况下,模式是贪婪的,这意味着尽可能多地匹配。因此,。{1,6}
只会在字符串末尾匹配少于6个字符。
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.
'abcdefghijklmnopqrstuvwxyz'.match(/.{1,6}/g);
结果:
["abcdef", "ghijkl", "mnopqr", "stuvwx", "yz"];
请注意,返回的对象是一个真正的数组。验证:
Note that the returned object is a true array. To verify:
console.log('.'.match(/./g) instanceof Array); //true
这篇关于将字符串拆分为等长字符串的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文