To split a string every N characters in JavaScript, call the match()
method on the string, passing as an argument this regular expression: /.{1, N}g/
. The match()
method will return an array containing substrings that each has N characters.
For example:
const str = 'codingbeauty';
const result = str.match(/.{1,4}/g) ?? [];
console.log(result); // [ 'codi', 'ngbe', 'auty' ];
The String
match()
method matches a string against a regular expression and returns an array of all the matches.
The forward slashes / /
indicate the start and end of the regular expression.
The .
(dot) metacharacter matches any single character in the string.
The braces in the form {min, max}
match at least min
characters and at most max
characters of the pattern preceding it. In our case, that pattern is the .
character, min
is 1
, and max is 4
, meaning that .{1, 4}
matches between 1 and 4 characters in the string.
We use the g
(global) flag to make every occurrence of the pattern in the string get matched. It makes the regex keep splitting the string by the N characters until it gets to the end.
Without the g
flag, only the first instance of the pattern will be matched.
const str = 'codingbeauty';
// "g" flag not specified
const result = str.match(/.{1,4}/) ?? [];
// [ 'codi' ... ] (single-item array)
console.log(result);
For a comprehensive guide to regular expression syntax, check out this cheat sheet from the MDN docs.
If there are no matches for the regex in the string, match()
returns null
. This is why we use the null coalescing operator (??
) to return an empty array ([]
) in such a case.
const str = '';
const result = str.match(/.{1,4}/g) || [];
console.log(result); // []
The ??
operator returns the value to its left if it is null
or undefined
. Otherwise, it returns the value to its right.
console.log(null ?? 5); // 5
console.log(2 ?? 5); // 2
console.log(undefined ?? 10); // 10
console.log('' ?? 10); // '' (empty string)
If the string’s length is not a multiple of N, the last element in the array will be less than N.
const str = 'codingbeautydev';
const result = str.match(/.{1,4}/g) ?? [];
// 👇 Last item is less than 4 characters long
console.log(result); // [ 'codi', 'ngbe', 'auty', 'dev' ];
Split string every N characters with for
loop
Alternatively, we can use a for
loop to split a string every N characters.
function splitString(str, N) {
const arr = [];
for (let i = 0; i < str.length; i += N) {
arr.push(str.substring(i, i + N));
}
return arr;
}
// [ 'codi', 'ngbe', 'auty' ]
console.log(splitString('codingbeauty', 4));
// [ 'codi', 'ngbe', 'auty', 'dev' ]
console.log(splitString('codingbeautydev', 4));
Our splitString()
function takes the string and the length each substring should have as arguments.
We use the for
loop to iterate over the string in increments of N. On each iteration, we call the String
substring()
method to get a substring between index i
and index i + N
exclusive in the string, and add the substring to the resulting array.
Split string every N characters with reduce()
method
Every time you see a for
loop used to process input to get output, it’s a sign that the code can be refactored to be made more functional and declarative, using one or more Array
methods.
Check out this method to split a string every N characters, where we use the reduce()
method to create some nice functional magic:
const splitString = (str, N) =>
[...str]
.reduce(
(substrings, ch) =>
(substrings.at(-1)?.length ?? N) < N
? [...substrings.slice(0, -1), substrings.at(-1) + ch]
: [...substrings, ch],
[]
);
// [ 'codi', 'ngbe', 'auty' ]
console.log(splitString('codingbeauty', 4));
// [ 'codi', 'ngbe', 'auty', 'dev' ]
console.log(splitString('codingbeautydev', 4));
I don’t recommend this though; as far as performance is concerned, it’s significantly (over 30 times) slower than the previous method, and might be harder to understand. I included it because it’s an elegant one-liner solution that works.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.