How to split a JavaScript string into fixed-length pieces?

Sometimes, we want to split a JavaScript string into fixed-length pieces.

In this article, we’ll look at how to split a JavaScript string into fixed-length pieces.

How to split a JavaScript string into fixed-length pieces?

To split a JavaScript string into fixed-length pieces, we can call the string’s match method with a regex.

For instance, we write:

const a = 'aaaabbbbccccee';
const b = a.match(/(.{1,4})/g);
console.log(b)

to call a.match with a regex that matches characters in groups of 4 throughout the string.

As a result, we get that b is ['aaaa', 'bbbb', 'cccc', 'ee'].

Conclusion

To split a JavaScript string into fixed-length pieces, we can call the string’s match method with a regex.