Borislav Hadzhiev
Tue Nov 23 2021·3 min read
Photo by Averie Woodard
To split a string into substring on N characters, call the match()
method on
the string, passing it the following regular expression /.{1, N}g/
. The
match
method will return an array containing substrings with length of N
characters.
const str = 'abcdabcdabcd'; const result = str.match(/.{1,4}/g) || []; // 👇️ ['abcd', 'abcd', 'abcd'] console.log(result)
The only parameter we passed to the String.match method is a regular expression.
The forward slashes / /
mark the beginning and end of the regular expression.
The dot .
special character matches any single character.
1
and at most 4
of the preceding characters (the dot, which matches any single character).We used the g
(global) flag because we want to match all occurrences of the
regular expression in the string, and not just the first occurrence.
If you need help reading a regular expression, check out this regex cheatsheet by the MDN docs, it has served me well over the years.
If the regex is not found in the string, the match
method returns null
. This
is why we used the logical OR (||) operator to return an empty array instead.
const str = ''; const result = str.match(/.{1,4}/g) || []; // 👇️ [] console.log(result);
If the string is not a multiple of N characters long, the last item in the array
would have a length of minimum 1
, but less than N.
const str = 'abcdabcdab'; const result = str.match(/.{1,4}/g) || []; // 👇️ ['abcd', 'abcd', 'ab'] console.log(result);
If you're looking to avoid regular expressions, use a for loop instead.
To split a string into substring on N characters:
function splitToSubstrings(str, n) { const arr = []; for (let index = 0; index < str.length; index += n) { arr.push(str.slice(index, index + n)); } return arr; } // 👇️ ['abcd', 'abcd'] console.log(splitToSubstrings('abcdabcd', 4));
We created a reusable function, which takes a string and the length the substrings should have as parameters.
We use a for loop to iterate over the string in increments of N.
On each iteration, we call the String.slice method to get a substring starting at the current index and going up to the index + N.
We passed the following 2 parameters to the slice
method:
After the loop has iterated over the string, we return the array of substrings.
This gets us the same result as using the match
method, but allows us to avoid
using regular expressions.
match
method, because the regular expression is not that bad and it's a bit more concise and direct than using a for loop.