javascriptstringreversein-place

How to reverse words in a string instead of reversing the whole string?


function reverseInPlace(str) {
    var words = [];
    words = str.split("\s+");
    var result = "";
    for (var i = 0; i < words.length; i++) {
        return result += words[i].split('').reverse().join('');
    }
}
console.log(reverseInPlace("abd fhe kdj"))

What I expect is dba ehf jdk, while what I'm getting here is jdk fhe dba. What's the problem?


Solution

  • you need to split the string by space

    function reverseInPlace(str) {
      var words = [];
      words = str.match(/\S+/g);
      var result = "";
      for (var i = 0; i < words.length; i++) {
         result += words[i].split('').reverse().join('') + " ";
      }
      return result
    }
    console.log(reverseInPlace("abd fhe kdj"))