Breaking a string into chunks of defined length and removing spaces using JavaScript

We are required to write a JavaScript function that takes in a string sentence that might contain spaces as the first argument and a number as the second argument.

Our function should first remove all the spaces from the string and then break the string into a number of chunks specified by the second argument.

All the string chunks should have the same length with an exception of last chunk, which might, in some cases, have a different length.

Solution Approach

The solution involves two main steps:

  • Remove all spaces using regex /\s/g
  • Split the cleaned string into chunks using a loop and slice() method

Example

Following is the complete implementation:

const num = 5;
const str = 'This is an example string';

const splitString = (str = '', num = 1) => {
    // Remove all spaces from the string
    str = str.replace(/\s/g, '');
    
    const arr = [];
    // Split string into chunks of specified length
    for(let i = 0; i < str.length; i += num){
        arr.push(str.slice(i, i + num));
    }
    return arr;
};

console.log(splitString(str, num));
[ 'Thisi', 'sanex', 'ample', 'strin', 'g' ]

How It Works

The function works in these steps:

  1. str.replace(/\s/g, '') removes all whitespace characters globally
  2. The loop increments by num to create chunks of the specified size
  3. str.slice(i, i + num) extracts each chunk from position i to i + num
  4. The last chunk automatically handles remaining characters if the string length isn't divisible by num

Alternative Example

Here's another example with different chunk size:

const text = 'JavaScript is awesome';
const chunkSize = 3;

console.log(splitString(text, chunkSize));
[ 'Jav', 'aSc', 'rip', 'tis', 'awe', 'som', 'e' ]

Conclusion

This function efficiently removes spaces and splits strings into equal-sized chunks using regex for space removal and the slice method for chunking. The last chunk automatically handles any remaining characters.

Updated on: 2026-03-15T23:19:00+05:30

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements