Search code examples
javascriptreversesentence

Reverse Sentences in JavaScript


function reverserStr(str){
   let word = str.split("").reverse().join("");
   return word;
}
console.log(reverserStr("I eat banana"));

what I expect is "banana eat I", while what I'm getting here is "ananab tae I", not sure what is missing


Solution

  • As you are splitting with "", you are getting an array of all the characters in the string which is being reversed. You should split with space character (" "):

    function reverserStr(str){
       let word = str.split(" ").reverse().join(" ");
       return word;
    }
    console.log(reverserStr("I eat banana"));