+ 4

Write a code that reverses a String automatically In JS

The code must NOT include substr() or substring() methods

14th Nov 2018, 5:43 PM
ArgyriosPournaris
ArgyriosPournaris - avatar
6 ответов
+ 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>
14th Nov 2018, 6:34 PM
Alex
+ 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.
14th Nov 2018, 6:30 PM
Maz
Maz - avatar
+ 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();
14th Nov 2018, 9:10 PM
ArgyriosPournaris
ArgyriosPournaris - avatar
+ 1
great...
15th Nov 2018, 9:20 AM
Vanumu Satish Kumar
Vanumu Satish Kumar - avatar
0
Where is your attempt?
14th Nov 2018, 5:50 PM
Diego
Diego - avatar
0
Push it in a array and pop it then you will get a reveresed string that's all!
14th Nov 2018, 6:32 PM
Adarsh.n. Bidari
Adarsh.n. Bidari - avatar