Split a String every N characters in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
3 min

banner

# Split a String every N characters in JavaScript

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.

index.js
const str = 'bobbyhadzabc'; const result = str.match(/.{1,4}/g) || []; // ๐Ÿ‘‡๏ธ [ 'bobb', 'yhad', 'zabc' ] console.log(result);

split string every n characters

The code for this article is available on GitHub

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

# Split a String every N characters using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the string every N characters.
  2. On each iteration, push a substring of N characters to an array.
  3. Return the array containing the substrings.
index.js
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));

split string every n characters using for loop

The code for this article is available on GitHub

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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe 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.

# Split a String every N characters using recursion

You can also use recursion to split a string every N characters.

index.js
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));

split string every n characters using recursion

The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev