Reversing strings with a twist in JavaScript

We are required to write a JavaScript function that takes in a string str as the first argument and an integer num as the second argument.

Our function should reverse the first num characters for every 2 * num characters counting from the start of the string. And if there are less than num characters left, we have to reverse all of them.

If there are less than 2 * num but greater than or equal to num characters, then we have to reverse the first num characters and leave the other as original.

For example −

If the input string and the number are −

const str = 'klmnopq';
const num = 2;

Then the output should be −

const output = 'lkmnpoq';

There we reversed the first 2 of the first 4 characters then moved on to find we are only left with 3 characters so we reversed the first 2 of the 3 characters.


The code for this will be −

 Live Demo

const str = 'klmnopq';
const num = 2;
const reverseString = (str = '', num = 1) => {
   if(str.length < num){
      return str.split("").reverse().join("");
   let res = "";
   for(let i = 0; i < str.length; i += (2*num)){
      res += str.split("").slice(i, i+num).reverse().join("");
      res += str.slice(i+num, i+2*num);
   return res;
console.log(reverseString(str, num));


And the output in the console will be −