Reversing a string in JavaScript

后端 未结 15 2013
野的像风
野的像风 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:21

    If it's necessary to revert the string, but return the original value of the error:

    function reverseString(s) {
        let valuePrintS;
        try {
            valuePrintS = s.split("").reverse().join("");    
        } catch {
            console.log("s.split is not a function");
            valuePrintS = s;
        } finally {
            console.log(valuePrintS);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 04:22
    String.prototype.strReverse = function() {
    
        var newstring = "";
    
        for (var s=0; s < this.length; s++) {
            newstring = this.charAt(s) + newstring;
        }
    
        return newstring;
    };
    
    0 讨论(0)
  • 2020-11-28 04:25

    reverse is a function on an array and that is a string. You could explode the string into an array and then reverse it and then combine it back together though.

    var str     = '0123456789';
    var rev_str = str.split('').reverse().join('');
    
    0 讨论(0)
  • 2020-11-28 04:28

    reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string:

    var backway = oneway.split("").reverse().join("");
    

    Update

    The method above is only safe for "regular" strings. Please see comment by Mathias Bynens below and also his answer for a safe reverse method.

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

    Google harder, bros. This is by Edd Mann.

    function reverse (s) {
    for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
    return o;
    }
    

    http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/

    http://jsperf.com/string-reverse-function-performance

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

    This is probably the way, acceptable for all browsers:

    function reverse(s) {
      var o = '';
      for (var i = s.length - 1; i >= 0; i--)
        o += s[i];
      return o;
    }
    

    Call it like a charm:

    reverse('your_string');
    
    0 讨论(0)
提交回复
热议问题