在JavaScript中以n大小的块拆分大字符串 [英] Split large string in n-size chunks in JavaScript
问题描述
我想将一个非常大的字符串(比方说,10,000个字符)分成N个大小的块。
I would like to split a very large string (let's say, 10,000 characters) into N-size chunks.
在性能方面最好的方法是什么要做到这一点?
What would be the best way in terms of performance to do this?
例如:
1234567890
除以2会变成 [12,34,56,78,90]
。
会不会像这可以使用 String.prototype.match
如果是这样,这会是表现最好的方式吗?
Would something like this be possible using String.prototype.match
and if so, would that be the best way to do it in terms of performance?
推荐答案
您可以这样做:
"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]
该方法仍适用于大小不是块大小的精确倍数的字符串:
The method will still work with strings whose size is not an exact multiple of the chunk-size:
"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]
一般情况下,对于你想要提取最多 n - 大小的子串的任何字符串,你可以这样做:
In general, for any string out of which you want to extract at-most n-sized substrings, you would do:
str.match(/.{1,n}/g); // Replace n with the size of the substring
如果您的字符串可以包含换行符或回车符,会做:
If your string can contain newlines or carriage returns, you would do:
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
就性能而言,我尝试了大约10k字符,在Chrome上花了一点多时间。 YMMV。
As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.
这也可用于可重复使用的功能:
This can also be used in a reusable function:
function chunkString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g'));
}
这篇关于在JavaScript中以n大小的块拆分大字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!