+ 4
Write a code that reverses a String automatically In JS
The code must NOT include substr() or substring() methods
6 Answers
+ 4
1) Example with minimal code to reverse the string:
<script>
function reverseString(s) {
return s.split("").reverse().join("");
}
var stringToReverse = prompt("Enter string to reverse:");
alert ("Reversed string:\n" + reverseString(stringToReverse));
</script>
2) Example using the traditional approach to reverse the string:
<script>
function reverseString(s) {
var reversedString = "";
for (var i = s.length - 1; i >= 0; i--) {
reversedString += s[i];
}
return reversedString;
}
var stringToReverse = prompt("Enter string to reverse:");
alert ("Reversed string:\n" + reverseString(stringToReverse));
</script>
+ 5
You can convert the string into an array, reverse the array and join the array elements to build the reversed string, and you can do all of this with just three simple methods!
Try it yourself.
+ 2
Thank all of you! I've already it! I Just wanted to See other possibilities of doing that, and I'm really impressed!! My code is:
var str = "w3schools";
function reverse() {
var l = str.length;
var arr = [];
var arr1 = [];
var i;
for(i=0; i<l; i++) {
arr[i] = str.slice(i, i+1);
}
for(i=0; i<arr.length; i++) {
arr1.unshift(arr[i]);
}
return arr1.join("").toString();
}
reverse();
+ 1
great...
0
Where is your attempt?
0
Push it in a array and pop it then you will get a reveresed string that's all!