faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

21 of 22 people (95%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How do I reverse a string?

Mar 11th, 2000 03:43
Martin Honnen,


The following adds a 
  reverse
method for String objects

  function stringReverse (str) {
    var s = typeof this.valueOf() == 'string' ? this : str;
    var r = '';
    for (var i = s.length - 1; i >= 0; i--)
      r += s.charAt(i);
    return r;
  }
  String.prototype.reverse = stringReverse;

which you can then call as in

  var s = 'Kibology';
  alert(s.reverse())

Note that the above function is quite flexible you don't have to call it 
as a method but can also pass the string in e.g.
   
  alert(stringReverse('Kibology'))