1

I want the text to be printed without commas.

<html> <head> <title>Reverse</title> </head> <body> <form name="rev"> Enter the string : <input type="text" name="str"/> <input type="button" value="click" onclick="rev1()" /><br> reverse of given string : <input type="text" name="res"/> </form> <script type="text/JavaScript"> function rev1(){ var a=rev.str.value; var b=[]; var i,j=0; for(i=a.length-1;i>=0;i--){ b[j]=a[i]; j++ } //rev.res.value=b; alert(b); } </script> </body> </html> 

If I give the input as abc I am getting an output as c,b,a, but I want it as cba.

1
  • [].toString() is implemented as [].join() (which uses a comma as a separator, by default, ie [].join(','). Commented Jul 29, 2012 at 12:07

3 Answers 3

13

Try this:

alert( b.join("") ) 

You could also reverse a string more easily by:

"hello".split("").reverse().join("") //"olleh" 
Sign up to request clarification or add additional context in comments.

Comments

3
  1. You may reverse your string using javascript built-in functions:

     <html> <head> <title>Reverse</title> </head> <body> <form name="rev"> Enter the string : <input type="text" name="str"/> <input type="button" value="click" onclick="rev1()" /><br> reverse of given string : <input type="text" name="res"/> </form> <script type="text/JavaScript"> function rev1(){ var a=rev.str.value; var b=a.split("").reverse().join(""); //rev.res.value=b; alert(b); } </script> </body> </html> 
  2. You may also transfer join your array elements to become a string

     <html> <head> <title>Reverse</title> </head> <body> <form name="rev"> Enter the string : <input type="text" name="str"/> <input type="button" value="click" onclick="rev1()" /><br> reverse of given string : <input type="text" name="res"/> </form> <script type="text/JavaScript"> function rev1(){ var a=rev.str.value; var b=[]; var i,j=0; for(i=a.length-1;i>=0;i--){ b[j]=a[i]; j++ } //rev.res.value=b; alert(b.join("")); } </script> </body> </html> 

Comments

0

You can also use document.getElementById().value.reverse().join("");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.