Reverse strings without changing the order of words in a sentence

前端 未结 4 1529
心在旅途
心在旅途 2020-12-20 22:25

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(         


        
相关标签:
4条回答
  • 2020-12-20 23:10

    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(" "));​
    
    0 讨论(0)
  • 2020-12-20 23:12

    Use this:

    var str = "Welcome to my Website !";
    alert(str.split("").reverse().join("").split(" ").reverse().join(" "));
    
    0 讨论(0)
  • 2020-12-20 23:21

    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 !
    
    0 讨论(0)
  • 2020-12-20 23:23

    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
    
    0 讨论(0)
提交回复
热议问题