Javascript - Reverse words in a sentence

北慕城南 提交于 2021-02-05 05:55:06

问题


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.


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



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



回答3:


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

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



回答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 words
var 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))


来源:https://stackoverflow.com/questions/30865704/javascript-reverse-words-in-a-sentence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!