在 JavaScript 中将大字符串拆分为 n 大小的块 [英] Split large string in n-size chunks in JavaScript

查看:40
本文介绍了在 JavaScript 中将大字符串拆分为 n 大小的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个非常大的字符串(比如 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"].

For instance: "1234567890" split by 2 would become ["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(/(.|[
]){1,n}/g); // Replace n with the size of the substring

就性能而言,我尝试了大约 10k 个字符,在 Chrome 上花了一秒钟多一点.天啊.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆