Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1325 Is there any way to reverse a string?

irt.org | Knowledge Base | JavaScript | Text | Q1325 [ previous next ]

Q1325 Is there any way to reverse a string?

JavaSscript 1.1 has array.reverse() but no string reverse.

Try this:

<script language="JavaScript"><!--
function strrev(str) {
   if (!str) return '';
   var revstr='';
   for (i = str.length-1; i>=0; i--)
       revstr+=str.charAt(i)
   return revstr;
}

alert(strrev("Hello World!"));
//--></script>

The following was submitted by Lee Kowalkowski

You can use split("") to convert a string to an array, reverse() to reverse the array, and join("") to convert it back.

<script language="javascript1.1"><!--
function strrev(str) {
  return str.split("").reverse().join("");
}

alert(strrev("Hello World!"));
//--></script>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.