Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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))

Solution 2:

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(" "));

Solution 3:

Add the following line before console log, you will get as expected

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

Solution 4:

Try this:

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

//split the string in to an array of wordsvar sp = a.split(" ");

for (i = 0; i < sp.length; i++) {
    //split the individual word into an array of char, reverse then join 
    sp[i] = sp[i].split("").reverse().join("");
}

//finally, join the reversed words back together, separated by " "var res = sp.join(" ");

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

Post a Comment for "Javascript - Reverse Words In A Sentence"