简体   繁体   中英

Reverse strings without changing the order of words in a sentence

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.

Use this:

var str = "Welcome to my Website !";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));

You can split on spaces, and then use map to reverse the letters in each word:

alert(str.split(" ").map(function(x) {
    return x.split("").reverse().join("");
}).join(" "));​

For older browser support you can try this,

var str = "Welcome to my Website !";

String.prototype.str_reverse= function(){
 return this.split('').reverse().join('');
}

var arr = str.split(" ");
for(var i=0; i<arr.length; i++){
 arr[i] = arr[i].str_reverse();
}

alert(arr.join(" ")); //OUTPUT: emocleW ot ym etisbeW !

I just solved this using a functional approach and typescript:

const  aString = "Our life always expresses the result of our dominant thoughts.";

function reverseString (str: string) :string {
  return  str.split('').reverse().join('')
}

function reverseWords(str:string) :string {
  return str.split(" ").map(reverseString).join(" ")
}

console.log(reverseWords(aString))
// ruO efil syawla sesserpxe eht tluser fo ruo tnanimod .sthguoht

You can also achieve this using:

[...word].reverse().join('')

Which in my opinion is a little bit cleaner

[...word] - makes an array out of string

.reverse() - reverses the array

.join('') - joins the array into a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM