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:
xxxxxxxxxx
1
const text = 'abcdefghijklmnop';
2
const result = text.match(/.{1,3}/g); // [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'p' ]
In this example, we use /.{1,3}/g
split string into chunks of 3
characters.
xxxxxxxxxx
1
const text = 'abcdefghijklmnop';
2
const regex = /.{1,3}/g;
3
4
const result = text.match(regex);
5
6
if (result) {
7
console.log(JSON.stringify(result)); // [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'p' ]
8
}
Note:
The last chunk's length may differ depending on the number of characters left.