OneCompiler

[Javascript] How to split a long string into smaller chunks of specific size?

I want to split a long string into smaller chunks of a specific length. How to do that in Javascript?

1 Answer

4 years ago by

You can either of the below regex to split the string into smaller chunks as shown below

Using Regex

let str= 'Hello world';
let chunkSize = 3;

let regex1 = new RegExp('.{1,' + chunkSize + '}', 'g'); 
console.log(str.match(regex1)); 

let regex2 = new RegExp("(.{" + chunkSize.toString() + "})");
console.log(str.split(regex2).filter(x => x.length != 0));

Run here https://onecompiler.com/javascript/3xnrq3z8v

4 years ago by Meera