你可以这样做:
"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]
该方法仍然适用于大小不是块大小的精确倍数的字符串:
"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]
一般来说,对于您最多要从中提取的任何字符串n- 大小的子字符串,你会这样做:
str.match(/.{1,n}/g); // Replace n with the size of the substring
如果你的字符串可以包含换行符或回车符,你会这样做:
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
就性能而言,我用大约 10k 字符进行了尝试,在 Chrome 上花了一秒多一点的时间。 YMMV。
这也可以用在可重用函数中:
function chunkString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g'));
}