JavaScript的优雅的方式来字符串分割成段N久的字符 [英] Javascript elegant way to split string into segments n characters long
本文介绍了JavaScript的优雅的方式来字符串分割成段N久的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所说,我有一个字符串,我想要分割成段的 N 长字符。
例如:
VAR海峡='ABCDEFGHIJKL';
一些魔术,其中n = 3后,将成为
VAR ARR = ['ABC','高清','GHI','JKL'];
有一种优雅的方式来做到这一点?
解决方案
str.match(/ {1,3} / G)
注意:使用 {1,3}
,而不是仅仅 {3}
以包括不为3的倍数为字符串长度的剩余部分,例如:
ABCD.match(/ {1,3} /克); // [A B C D]
一对夫妇更细微之处:
- 如果您的字符串可以包含换行符(要算作一个字符,而不是分割字符串的),那么
。
荣获' T捕捉这些。使用/ [\\ S \\ S] {1,3} /
来代替。 (感谢@Mike)。 - 如果您的字符串为空,则
匹配()
将返回空
时,你可能会期望一个空数组。防止这种通过追加|| []
。
所以,你可能结了:
VAR部分= str.match(/ [\\ S \\ S] {1,3} / G)|| [];
As the title says, I've got a string, and I want to split into segments n characters long.
For example:
var str = 'abcdefghijkl';
after some magic with n=3, will become
var arr = ['abc','def','ghi','jkl'];
Is there an elegant way to do this?
解决方案
str.match(/.{1,3}/g)
Note: Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
"abcd".match(/.{1,3}/g); // ["abc", "d"]
A couple more subtleties:
- 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|| []
.
So you may end up with:
var parts = str.match(/[\s\S]{1,3}/g) || [];
这篇关于JavaScript的优雅的方式来字符串分割成段N久的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文