0
String.prototype.reverseStr = function () {
    var len = this.length - 1;
    var j = 0;
    for (i = len; i >= Math.floor(len / 2); i--) {
        var tmp = this[i];
        this[i] = this[j];
       this[j] = tmp;
       j++;
    }
    return this;
}

alert("abcde".reverseStr());

Why doesn't this work ? It outputs "abcde" and not reversed string .

2 Answers 2

2

Overkill.

 "abcde".split('').reverse().join('');
Sign up to request clarification or add additional context in comments.

3 Comments

1+ And it's surprisingly faster than most other methods too. (at least in modern browsers). jsperf.com/string-reverse/4
I got this . But what if I have write my own string function. Why doest the above code work.
@rrmo, Strings are immutable.
-1

The same code but with some edits

String.prototype.reverseStr = function () {
    var len = this.length - 1;
    var tmp = '';
    for (var i = len; i >= 0; i--) {
        tmp += this[i];
    }
    return tmp;
}

alert("abcde".reverseStr());

See a fiddle here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.