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))
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))
+10
source to share