Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse strings without changing the order of words in a sentence

Tags:

javascript

My Code:

I tried the following code but the order of words are changing

var str = "Welcome to my Website !";

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

It is giving result as

! etisbeW ym ot emocleW

But I need the result as

emocleW ot ym etisbeW !

That is, I don't want to change the order of words.

like image 826
Programmer Avatar asked Dec 06 '12 05:12

Programmer


People also ask

How do you reverse a string without changing order?

Simple Solution:Copy alphabetic characters from the given array to temp[]. Reverse temp[] using standard string reversal algorithm. Now traverse input string and temp in a single loop. Wherever there is an alphabetic character is input string, replace it with the current character of temp[].

How do you reverse the order of words in a sentence?

In more simple language, the first word will be placed at the last position whereas the last word will come at the first place, the second word will be placed at the second last word's position and the second last word will come at the second place, and so on. In this way, our whole sentence is to be reversed.


1 Answers

Use this:

var str = "Welcome to my Website !";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));
like image 135
Md. Mahbubul Haque Avatar answered Oct 20 '22 00:10

Md. Mahbubul Haque