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.


Following is the code −

 Live Demo

const num = 5;
const str = 'This is an example string';
const splitString = (str = '', num = 1) => {
   str = str.replace(/\s/g,'');
   const arr = [];
   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' ]