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. 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 others as original.

Example Input and Output

If the input string and the number are:

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

Then the output should be:

'lkmnpoq'

Here we reversed the first 2 of the first 4 characters ('kl' becomes 'lk'), then moved on to find we are only left with 3 characters ('nop'), so we reversed the first 2 of those 3 characters ('no' becomes 'on'), leaving 'p' unchanged.

How It Works

The algorithm processes the string in chunks of 2 * num characters. For each chunk:

  • Reverse the first num characters
  • Keep the next num characters unchanged
  • If fewer than num characters remain, reverse all remaining characters

Implementation

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));
lkmnpoq

Step-by-Step Breakdown

Let's trace through the example with str = 'klmnopq' and num = 2:

const traceReverseString = (str = '', num = 1) => {
    console.log(`Input: "${str}", num: ${num}`);
    
    if(str.length < num){
        const result = str.split("").reverse().join("");
        console.log(`String length < num, reversing entire string: "${result}"`);
        return result;
    };
    
    let res = "";
    for(let i = 0; i < str.length; i += (2*num)){
        const chunk = str.slice(i, i+2*num);
        const toReverse = str.slice(i, i+num);
        const toKeep = str.slice(i+num, i+2*num);
        
        console.log(`Chunk ${i/4 + 1}: "${chunk}"`);
        console.log(`  Reverse: "${toReverse}" ? "${toReverse.split("").reverse().join("")}"`);
        console.log(`  Keep: "${toKeep}"`);
        
        res += str.split("").slice(i, i+num).reverse().join("");
        res += str.slice(i+num, i+2*num);
        
        console.log(`  Result so far: "${res}"`);
    };
    return res;
};

console.log("Final result:", traceReverseString('klmnopq', 2));
Input: "klmnopq", num: 2
Chunk 1: "klmn"
  Reverse: "kl" ? "lk"
  Keep: "mn"
  Result so far: "lkmn"
Chunk 2: "opq"
  Reverse: "op" ? "po"
  Keep: "q"
  Result so far: "lkmnpoq"
Final result: lkmnpoq

Additional Examples

// Test with different inputs
console.log(reverseString('abcdef', 3));     // "cbafed"
console.log(reverseString('hello', 2));      // "ehllowrd"
console.log(reverseString('xyz', 5));        // "zyx" (entire string reversed)
console.log(reverseString('programming', 4)); // "gorpmmargnig"
cbafed
ehllo
zyx
gorpmargnig

Conclusion

This string reversal algorithm processes text in chunks, selectively reversing portions while preserving others. It's useful for creating patterns or implementing specific text transformation requirements in JavaScript applications.

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

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements