Split string into equal parts JavaScript

We are required to write a JavaScript function that takes in a string and a number n as two arguments (the number should be such that it exactly divides the length of string). And we have to return an array of n strings of equal length.

For example −

If the string is "helloo" and the number is 3
Our output should be:
["ho", "eo", "ll"]

Here, each substring exactly contains (length of array/n) characters. And each substring is formed by taking corresponding first and last letters of the string alternatively

Let's write the code for this function −


const str = 'helloo';
const splitEqual = (str, n) => {
   if(str.length % n !== 0){
      return false;
   const len = str.length / n;
   const strArray = str.split("");
   const arr = [];
   let i = 0, char;
      if(i % 2 === 0){
         char = strArray.shift();
         char = strArray.pop();
      if(i % len === 0){
         arr[i / len] = char;
         arr[Math.floor(i / len)] += char;
   return arr;
console.log(splitEqual(str, 3));


The output in the console will be −

[ 'ho', 'eo', 'll' ]

Updated on: 31-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started