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
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
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.
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("");
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('');
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 :)
//
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
*/