每个单词的Javascript字符串反向

时间:2014-11-17 05:15:15

标签: javascript

我有一个字符串"这应该更好",我需要将它作为" sihT dlouhs eb retteb"

我能够分割字符串,但之后我无法撤消它。

str="This should be better"
str.split(" ")
//["This", "should", "be", "better"]

在此之后如何将其反转为" sihT dlouhs eb retteb"

4 个答案:

答案 0 :(得分:5)

试试这个

str.split("").reverse().join("").split(" ").reverse().join(" ");

答案 1 :(得分:0)

这是我在网上找到的相同解决方案,但我也添加了自己的解释。 以下代码的工作方式如下:

输入:

var str = "Hi Iam Faizan";

输出:

var outputstr = "iH maI naziaF";

代码:

var strr = str.split("");//slices all char
var str2 = strr.reverse();// reverse all //char string
var str3 = str2.join("");// merge the reversed characters into one string
var str4 = str3.split(" ");//seperate them with spaces
var str5 = str4.reverse();// reverse the comma separated words back to their original sequence
console.log(str5.join(" "));//finally make them all as one string and separate them with spaces

答案 2 :(得分:0)

尝试使用for循环:

let str = "This should be better"
let output = "", word = " ";

for (let i = 0; i < str.length; i++) {
    if (str.charAt(i) !== " ") {
        word = str.charAt(i) + word
    } else {
        output += word;
        word = " "
    }
}

console.log(output + word);

答案 3 :(得分:-1)

怎么样:

for (var i = 0, len = str.length; i <= len; i++) {
   str[i].split('').reverse().join('');
}