Reversing a string in JavaScript

I'm trying to reverse an input string

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

but firebug is telling me that oneway.reverse() is not a function. Any ideas?

Thank you

Answers:

Answer

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.

Answer

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

Answer
// 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
*/
Answer

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('');
Answer

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');
Answer

I think you'll find that in fact reverse() isn't a function in jQuery. Incidentally, jQuery is really good at manipulating your DOM, but isn't really for string manipulation as such (although you can probably get plugins/write your own) to do this.

The best way I've found to reverse a string in javascript is to do the following:

String.prototype.reverse = function(){
splitext = this.split("");
revertext = splitext.reverse();
reversed = revertext.join("");
return reversed;
}

Found at: http://www.bytemycode.com/snippets/snippet/400/

I think you'll find that if you pop the above into your code somewhere, your call to .reverse() should work :)

Answer

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: ???? is an astral
//symbol, and JavaScript exposes it as two separate code units.
function ReverseString(string){
    //-
    var regexSymbolWithCombiningMarks = /([\0-\u02FF\u0370-\u1DBF\u1E00-\u20CF\u2100-\uD7FF\uDC00-\uFE1F\uFE30-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF])([\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]+)/g;
    var regexSurrogatePair = /([\uD800-\uDBFF])([\uDC00-\uDFFF])/g;
    //-

    //Step 1: deal with combining marks and astral symbols (surrogate pairs)
    string = string
        //Swap symbols with their combining marks so the combining marks go first
        .replace(regexSymbolWithCombiningMarks, function($0, $1, $2) {
            return reverse($2) + $1;
        })
        // Swap high and low surrogates so the low surrogates go first
        .replace(regexSurrogatePair, '$2$1');

    // Step 2: reverse the code units in the string
    var result = '';
    var index = string.length;
    while (index--) {
        result += string.charAt(index);
    }

    //Return value
    return result;
}
Answer

This reverse prototype function is implemented using "this". If you see log console of "this", it will generate the array, and it has length property. So that it!!! Just use reverse "for-loop" as shown in the code snippet.

String.prototype.reverse = function () {
    console.log(this);
    var result = "";
    var len = this.length;
    
    for (i = (len-1); i >= 0 ; i--) {
        result += this[i];
    }
    return result;
};

alert("elahnu jaknap".reverse());

Answer

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');
Answer

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);
    }
}
Answer
String.prototype.strReverse = function() {

    var newstring = "";

    for (var s=0; s < this.length; s++) {
        newstring = this.charAt(s) + newstring;
    }

    return newstring;
};
Answer

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 ???? bar');
// ? 'rab ?? oof'
// Where did the `????` symbol go? Whoops!

If you’re wondering why this happens, read up on JavaScript’s internal character encoding. (TL;DR: ???? is an astral symbol, and JavaScript exposes it as two separate code units.)

But there’s more:

// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('mañana man?ana');
// ? 'ana?nam anañam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.

A good string to test string reverse implementations is the following:

'foo ???? bar mañana man?ana'

Why? Because it contains an astral symbol (????) (which are represented by surrogate pairs in JavaScript) and a combining mark (the n? in the last man?ana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).

The order in which surrogate pairs appear cannot be reversed, else the astral symbol won’t show up anymore in the ‘reversed’ string. That’s why you saw those ?? marks in the output for the previous example.

Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. That’s why the example output had a? instead of ñ.

Hopefully, this explains why all the answers posted so far are wrong.


To answer your initial question — how to [properly] reverse a string in JavaScript —, I’ve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesn’t have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.

var input = 'foo ???? bar mañana man?ana';
esrever.reverse(input);
// ? 'anan?am anañam rab ???? oof'
Answer
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.

Answer
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>


        $(document).ready(function () {

            $("#stringInput").keyup(function () {
                debugger;
                var string = $("#stringInput").val();
                var stringArray = [];
                sInput = string.toString();

                for (var i = 0, len = sInput.length; i < len; i++) {

                    stringArray.push(sInput.charAt(i));
                }
                stringArray.reverse();
                str = stringArray.join('');


                document.getElementById("stringOutput").value = str;

            });

            $("button").click(function () {
                debugger;
                $("#myForm").toggle();
            });
        });

    </script>
</head>

<body>

     <div>
        <form name="myForm" id="myForm">

    <table>
        <tr>
            <td>Insert Elements :</td>
            <td><input type="text" name="stringInput" id="stringInput"/></td>

            <td>Output :</td>
            <td><input type="text" id="stringOutput" name="stringOutput" readonly="true" /></td>
        </tr>

    </table>
      </form>
         <button>Show/Hide</button>
    </div>
</body>
</html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.