Reversing a string in JavaScript

后端 未结 15 2015
野的像风
野的像风 2020-11-28 03:58

I\'m trying to reverse an input string

var oneway = document.getElementById(\'input_field\').value();
var backway = oneway.reverse();

but f

相关标签:
15条回答
  • 2020-11-28 04:36

    Use this simple method to reverse the words of a string at its position

     function fun(str){
         var arr1=str.split(' ');
         console.log(arr1);
         var strings='',rever='';
         for(var i=0;i<arr1.length;i++)
         {
            strings=arr1[i].split('');
            rever+=strings.reverse().join('')+' ';  
         }
         console.log(rever.split(' '));
         console.log(rever.trim());
     };
     fun('javascript is fun');
    
    0 讨论(0)
  • 2020-11-28 04:37

    Reverse String using function parameter with error handling :

    function reverseString(s) 
    {
       try
       {
          console.log(s.split("").reverse().join(""));
       }
       catch(e)
       {
          console.log(e.message);
          console.log(s);
       }   
    }
    
    0 讨论(0)
  • 2020-11-28 04:39

    The following technique (or similar) is commonly used to reverse a string in JavaScript:

    // Don’t use this!
    var naiveReverse = function(string) {
        return string.split('').reverse().join('');
    }
    

    In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:

    naiveReverse('foo                                                                     
    0 讨论(0)
  • 2020-11-28 04:40
    String.prototype.reverse = function () {
        return this.split("").reverse().join("");
    }
    

    Inspired by the first result I got when I did a Google for javascript string reverse.

    0 讨论(0)
  • 2020-11-28 04:45

    Mathias Bynens, your code works grate, thanks a lot!

    I convert your code to a function, in this way users are able to copy it from here.

    Thanks!

    //The function reverse a string,  JavaScript’s has internal character encoding so we are
    //unable to reverse the string in the "easy ways". For example the TL;DR:                                                                     
    0 讨论(0)
  • 2020-11-28 04:46
    // You could reverse a string without creating an array
    
    String.prototype.reverse= function(){
     var s= '', L= this.length;
     while(L){
      s+= this[--L];
     }
     return s;
    }
    
    var s1= 'the time has come, the walrus said, to speak of many things';
    s1.reverse()
    /*returned value: (String)
    sgniht ynam fo kaeps ot, dias surlaw eht, emoc sah emit eht
    */
    
    0 讨论(0)
提交回复
热议问题