EN
JavaScript - split string into segments of n characters
0
points
In this article, we would like to show you how to split a string into segments of n characters in JavaScript.
Quick solution:
const text = 'abcdefghijklmnop';
const result = text.match(/.{1,3}/g); // [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'p' ]
Practical example
In this example, we use /.{1,3}/g split string into chunks of 3 characters.
// ONLINE-RUNNER:browser;
const text = 'abcdefghijklmnop';
const regex = /.{1,3}/g;
const result = text.match(regex);
if (result) {
console.log(JSON.stringify(result)); // [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'p' ]
}
Note:
The last chunk's length may differ depending on the number of characters left.