How to Split a JavaScript String by "n" Characters Into an Array?

You can split a JavaScript string by "n" characters into an array in the following ways:

Using Regular Expression

You can use the String.prototype.match() method with a regular expression to split the string by n number of characters.

For example, to split a string at every three characters, you can do the following:

// ES11+
const splitStr = (str) => str.match(/.{3}/g) ?? [];

console.log(splitStr('foobarbazqux')); // ['foo', 'bar', 'baz', 'qux']
console.log(splitStr('foobarbazqu')); // ['foo', 'bar', 'baz']
console.log(splitStr('foobarbazq')); // ['foo', 'bar', 'baz']

console.log(splitStr('')); // []
console.log(splitStr('f')); // []
console.log(splitStr('fo')); // []

This code uses the global flag (g) with the regular expression to match all occurrences of "n" characters in the string, and returns an array of the resulting chunks. The nullish coalescing operator (??) is used to return an empty array when there are no matches, instead of returning null.

The nullish coalescing operator was added in ES11. Therefore, you can remove/replace it if you wish to support versions of ES earlier than that.

If you want to include the remaining characters at the end of the string that are not "n" characters long, you can modify the regular expression to match between 1 and "n" characters, for example, like so:

// ES11+
const splitStr = (str) => str.match(/.{1,3}/g) ?? [];

console.log(splitStr('foobarbazqux')); // ['foo', 'bar', 'baz', 'qux']
console.log(splitStr('foobarbazqu')); // ['foo', 'bar', 'baz', 'qu']
console.log(splitStr('foobarbazq')); // ['foo', 'bar', 'baz', 'q']

console.log(splitStr('')); // []
console.log(splitStr('f')); // ['f']
console.log(splitStr('fo')); // ['fo']

Iterating Over the String

In JavaScript, strings are iterable (which means that you can loop over them using a for loop or other iteration methods). Therefore, you can simply loop over the string to extract chunks of characters at every "n-th" iteration and add them to a new array, ultimately splitting the string into multiple chunks.

For example, you can split a string into chunks of up to three characters in the following way:

function splitStr(str, chunkSize = 3) {
    const chunks = [];

    for (let i=0; i<str.length; i += chunkSize) {
        chunks.push(str.substring(i, i + chunkSize));
    }

    return chunks;
}

console.log(splitStr('foobarbazqux')); // ['foo', 'bar', 'baz', 'qux']
console.log(splitStr('foobarbazqu')); // ['foo', 'bar', 'baz', 'qu']
console.log(splitStr('foobarbazq')); // ['foo', 'bar', 'baz', 'q']

console.log(splitStr('')); // []
console.log(splitStr('f')); // ['f']
console.log(splitStr('fo')); // ['fo']

This code uses a for loop to iterate over the string and extract substrings of "n" characters using the String.prototype.substring() method. It then adds each chunk to an array, and returns it. The remaining characters at the end of the string that are less than "n" characters long are included in the result.

To discard any remaining characters at the end of the string that are less than "n" characters long, you can add an if statement to check the length of the extracted chunk before adding it to the array, for example, like so:

function splitStr(str, chunkSize = 3) {
    const chunks = [];

    for (let i=0; i<str.length; i += chunkSize) {
        const chunk = str.substring(i, i + chunkSize);
        if (chunk.length === chunkSize) {
            chunks.push(str.substring(i, i + chunkSize));
        }
    }

    return chunks;
}

console.log(splitStr('foobarbazqux')); // ['foo', 'bar', 'baz', 'qux']
console.log(splitStr('foobarbazqu')); // ['foo', 'bar', 'baz']
console.log(splitStr('foobarbazq')); // ['foo', 'bar', 'baz']

console.log(splitStr('')); // []
console.log(splitStr('f')); // []
console.log(splitStr('fo')); // []

This code checks if the extracted chunk has the same length as "chunkSize" before adding it to the array, effectively discarding any remaining characters at the end of the string that are less than the specified characters long.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.