如何将字符串拆分为 n 个字符的段? [英] How can I split a string into segments of n characters?
本文介绍了如何将字符串拆分为 n 个字符的段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所说,我有一个字符串,我想分成 n 个字符的片段.
As the title says, I've got a string and I want to split into segments of n characters.
例如:
var str = 'abcdefghijkl';
经过n=3
的一些魔法后,它会变成
after some magic with n=3
, it will become
var arr = ['abc','def','ghi','jkl'];
有没有办法做到这一点?
Is there a way to do this?
推荐答案
var str = 'abcdefghijkl';
console.log(str.match(/.{1,3}/g));
注意: 使用 {1,3}
而不是 {3}
来包含不是字符串长度的余数3 的倍数,例如:
Note: Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
还有一些微妙之处:
- 如果您的字符串可能包含换行符(您想将其视为一个字符而不是拆分字符串),那么
.
将不会捕获这些.使用/[\s\S]{1,3}/
代替.(感谢@Mike). - 如果您的字符串为空,那么当您期望一个空数组时,
match()
将返回null
.通过附加|| 来防止这种情况[]
.
- If your string may contain newlines (which you want to count as a character rather than splitting the string), then the
.
won't capture those. Use/[\s\S]{1,3}/
instead. (Thanks @Mike). - If your string is empty, then
match()
will returnnull
when you may be expecting an empty array. Protect against this by appending|| []
.
所以你可能会得到:
var str = 'abcdef \t\r\nghijkl';
var parts = str.match(/[\s\S]{1,3}/g) || [];
console.log(parts);
console.log(''.match(/[\s\S]{1,3}/g) || []);
这篇关于如何将字符串拆分为 n 个字符的段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文