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
.
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
.
3 Answers
Reset to default 13Try this:
alert( b.join("") )
You could also reverse a string more easily by:
"hello".split("").reverse().join("")
//"olleh"
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>
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>
You can also use document.getElementById().value.reverse().join("");
[].toString()
is implemented as[].join()
(which uses a comma as a separator, by default, ie[].join(',')
. – Rob W Commented Jul 29, 2012 at 12:07