Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Reverse words in a sentence

Please refer - 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 does not reverse and is not outputted in the final result. Not sure what is missing.

like image 836
gopal rao Avatar asked Jan 23 '26 22:01

gopal rao


2 Answers

It problem is your if(a[i] == " ") condition is not satisfied 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))

You can also try a shorter

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))
like image 190
Arun P Johny Avatar answered Jan 26 '26 11:01

Arun P Johny


I don't know wich one is the best answer I'll live you mine 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(" "));
like image 20
Su4p Avatar answered Jan 26 '26 11:01

Su4p