Chop string into chunks of given length

Write a function to chop string into chunks of given length and return it as array.

Example

Input:
'javascript'
3

Output:
['jav','asc','rip','t']

We can solve this problem with two different approaches.

1. Bruteforce.
2. Regex.


Bruteforce approach

It is extremely straight forward, iterate each character of the string and keep on slicing the characters of the given size and pushing it into the output array.

const chop = (str, size = str.length) => {
    const arr = [];
    let i = 0;
    
    //iterate the string
    while (i < str.length) {
        //slice the characters of given size
        //and push them in output array
        arr.push(str.slice(i, i + size));
        i = i + size;
    }
  
    return arr;
}
Input:
console.log(chop('javascript', 3));

Output:
["jav","asc","rip","t"]

Using Regex

We often tend to ignore the Regex based solution as it is not easy to remeber the expressions, but the Regex method accepts the size which can be used to extract at-most n-sized sub strings.

Syntax

str.match(/.{1,n}/g); // Replace n with the size of the substring

If the string contains any newlines or carriage returns, then use this expression.

str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring

String​.prototype​.match() returns an array of matching string with a regular expression. Passing the regex to it will returns the array of n-sized sub strings.

const chop = (str, size = str.length) => {
    return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Input:
console.log(chop('javascript', 3));

Output:
["jav","asc","rip","t"]