Last updated: Mar 4, 2024
Reading timeยท3 min
To split a string every 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 a length of
N characters.
const str = 'bobbyhadzabc'; const result = str.match(/.{1,4}/g) || []; // ๐๏ธ [ 'bobb', 'yhad', 'zabc' ] console.log(result);
The String.match() method matches a string against a regular expression.
The method returns an array containing the matches (if any) or null
if no
matches are found.
The forward slashes / /
mark the beginning and end of the regular expression.
The dot .
special character matches any single character.
The curly braces {min, max}
match at least min
characters and at most max
characters of the preceding item.
In the example, .{1,4}
matches between 1 and 4 characters of the string.
const str = 'bobbyhadzabc'; const result = str.match(/.{1,4}/g) || []; // ๐๏ธ [ 'bobb', 'yhad', 'zabc' ] console.log(result);
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 remove the g
flag, only the first occurrence of the regex is matched in
the string.
const str = 'bobbyhadzabc'; const result = str.match(/.{1,4}/) || []; // ๐๏ธ [ 'bobb' ] console.log(result);
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);
The logical OR (||) operator returns the value to the right if the value to the left is falsy.
If the string's length is not a multiple of N, the last item in the array would
have a length of minimum 1
, but less than N.
const str = 'bobbyhadz.com'; const result = str.match(/.{1,4}/g) || []; // ๐๏ธ [ 'bobb', 'yhad', 'z.co', 'm' ] console.log(result);
If you're looking to avoid regular expressions, use a for
loop instead.
for
loopThis is a three-step process:
for
loop to iterate over the string every N characters.function splitEveryN(str, n) { const arr = []; for (let index = 0; index < str.length; index += n) { arr.push(str.slice(index, index + n)); } return arr; } // ๐๏ธ [ 'bobb', 'yhad', 'zabc' ] console.log(splitEveryN('bobbyhadzabc', 4)); // ๐๏ธ [ 'bo', 'bb', 'yh', 'ad', 'za', 'bc' ] console.log(splitEveryN('bobbyhadzabc', 2));
The splitEveryN()
function takes a string and n
as parameters and splits the
string every N characters.
We used 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.
The String.slice() method extracts a section of a string and returns it, without modifying the original string.
The String.slice()
method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
After the for
loop has iterated over the string, we return the array
containing the results.
You can also use recursion to split a string every N characters.
function splitEveryN(str, n, arr = []) { if (str.length === 0) { return arr; } arr.push(str.slice(0, n)); return splitEveryN(str.slice(n), n, arr); } // ๐๏ธ [ 'bobb', 'yhad', 'zabc' ] console.log(splitEveryN('bobbyhadzabc', 4)); // ๐๏ธ [ 'bo', 'bb', 'yh', 'ad', 'za', 'bc' ] console.log(splitEveryN('bobbyhadzabc', 2));
The function takes the string an n
as parameters and splits the string every N
characters.
If the string's length is equal to 0
, we return the array as we have finished
splitting the string.
Otherwise, we use the Array.push()
method to push a slice of the string from
index 0
to index N
.
The last step is to call the function again with the remainder of the string,
n
and the array as parameters.
You can learn more about the related topics by checking out the following tutorials: