0

I have a string "This should be better", i need to make it as " sihT dlouhs eb retteb"

I am able to split the string but after that i am unable to reverse it.

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

After this how to reverse it as "sihT dlouhs eb retteb"

4 Answers 4

5

Try this

str.split("").reverse().join("").split(" ").reverse().join(" ");
Sign up to request clarification or add additional context in comments.

Comments

0

And here is the same solution I found online but I have also added my own explanation. The following code will work like:

Input:

var str = "Hi Iam Faizan";

Output:

var outputstr = "iH maI naziaF";

Code:

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

Comments

0

Try this with for loop :

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

Comments

-1

How about:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.