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.
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))
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(" "));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With