Javascript - Reverse words in a sentence

Please refer to https://jsfiddle.net/jy5p509c/

var a = "who all are coming to the party and merry around in somewhere";

res = ""; resarr = [];

for(i=0 ;i<a.length; i++) {

if(a[i] == " ") {
    res+= resarr.reverse().join("")+" ";
    resarr = [];
}
else {
    resarr.push(a[i]);
}   
}
console.log(res);

      

The last word is not canceled or displayed in the final result. Not sure what is missing.

+3


source to share


3 answers


The problem is that your condition if(a[i] == " ")

fails for the last word

var a = "who all are coming to the party and merry around in somewhere";

res = "";
resarr = [];

for (i = 0; i < a.length; i++) {
  if (a[i] == " " || i == a.length - 1) {
    res += resarr.reverse().join("") + " ";
    resarr = [];
  } else {
    resarr.push(a[i]);
  }
}

document.body.appendChild(document.createTextNode(res))
      

Run codeHide result





You can also try shorter ones

var a = "who all are coming to the party and merry around in florida";

var res = a.split(' ').map(function(text) {
  return text.split('').reverse().join('')
}).join(' ');

document.body.appendChild(document.createTextNode(res))
      

Run codeHide result


+10


source


I don't know which one is the best answer. I will live for you and let you decide, here it is:



console.log( 'who all are coming to the party and merry around in somewhere'.split('').reverse().join('').split(" ").reverse().join(" "));

      

+1


source


Add the following line to the console log, you get as expected

res+= resarr.reverse().join("")+" ";

      

0


source







All Articles