Splitting a string into parts in JavaScript


We are required to write a JavaScript function that takes in a string and a number n (such that n exactly divides the length of string) and we need to return an array of string of length n containing n equal parts of the string.

Example

The code for this will be −

const str = 'we will be splitting this string into parts';
const num = 6;
const divideEqual = (str, num) => {
   const len = str.length / num;
   const creds = str.split("").reduce((acc, val) => {
      let { res, currInd } = acc;
      if(!res[currInd] || res[currInd].length < len){
         res[currInd] = (res[currInd] || "") + val;
      }else{
         res[++currInd] = val;
      };
      return { res, currInd };
   }, {
      res: [],
      currInd: 0
   });
   return creds.res;
};
console.log(divideEqual(str, num));

Output

The output in the console −

[ 'we will ', 'be split', 'ting thi', 's string', ' into pa', 'rts' ]

Updated on: 14-Oct-2020

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements