views:

623

answers:

5

I'm trying to reverse an input string

var oneway = $('#inputfield').val();
var backway = oneway.reverse();

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

Thank you

+3  A: 
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.

Brian Campbell
There's some controversy about extending built-in classes like String, but nice answer! :)
Ates Goral
+6  A: 

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("");
Ates Goral
Thank you Ates.
drummer
+1  A: 

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('');
Alex Sexton
A: 

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 :)

Iain Fraser
A: 
//
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
*/
kennebec