[SOLVED] Reverse a string algorithm – JavaScript

Issue

I’m trying to solve this algorithm but am getting undefined at the beginning. Can anybody explain why this is happening so I may solve it?

// Given a String S, reverse the string without reversing its individual words. Words are separated by dots.

function reverseStr(str){
    newStr="";
    for(var i=str.length;i>=0;i--){
        newStr+=str[i];
    }
    console.log(newStr);
}

reverseStr("hcum.yrev.margorp.siht.ekil.i");

Output: undefinedi.like.this.program.very.much

Solution

Strings are indexed starting from 0, so the last index is 1 less than the string’s length. That means you should do var i=str.length-1 instead of var i=str.length.

Answered By – Orius

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.