One of the first code/algorithm challenges that we set out to solve as budding software engineers and web developers is to see if we can figure out how to reverse a string. Remember that a string is just a collection of characters and spaces. What we need to set out to do is to try to reverse, for example, the string “Hello World!” and return “!dlroW olleH”. There are several ways we can solve this problem and we’ll cover a few of them here in this article.
The Prompt
Write a function, reverseString
, that reverses a string and returns it. The string to reverse is given as an argument in the function.
Solution # 1: For Loop
The first, and probably one of the most straightforward solutions is to use a for loop and go backwards through the string. We’ll need to instantiate, or create, a variable that holds the new reversed string as we pass each character in the string:
function reverseString(str) { let newStr = ''; for(let i = str.length - 1; i >= 0; i--) { newStr += str[i]; } return newStr; }
We assign i to the last index (which is figured out when we take 1 from the length of the string) ⇒ this is our initialization and will serve as the first index we loop through. The second portion of the for loop is our condition ⇒ this tells the loop when to stop. The third and last portion of the for loop is how much our i will increment after completion of the loop and the condition still holds true : i– essentially takes our i and reassigns it to i – 1;
As we loop through each iteration we take each character at str[i] and add it to the newStr. We then return the newStr outside of our for loop and terminate the function.
Try it yourself in the code editor:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="" /> <script> function reverseString(str) { let newStr = ''; for(let i = str.length - 1; i >= 0; i--) { newStr += str[i]; } return newStr; } function showInput(e) { e.preventDefault(); const inputStr = document.getElementById('user_input').value; if(inputStr.length < 1) { alert("Must enter a string to reverse. Try again.") } let reversed = reverseString(inputStr); document.getElementById( 'display' ).innerHTML = reversed; document.getElementById('user_input').value = ''; } </script> <style> * { box-sizing: border-box;; } body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } #user_input { width: 100%; } #submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } #display { font-size: 1.4rem; height: 50px; } </style> </head> <body> <div> <form onsubmit="showInput(event);"> <label id="label">Enter a String to Reverse:</label> <input type="text" name="message" id="user_input"/> <input type="submit" onclick="showInput(event);" id="submit_button"/><br /> <label>Your input: </label> <p><span id="display"></span></p> </form> </div> </body> </html>
Solution # 2: JavaScript’s ES6 map method
JavaScript has a built in array method that was new to ES6 called map. What this does is it returns a new array with the specified values. The map method has three parameters: The current item, the index of the item, and a copy of the array it’s coming from. We will use the last two parameters in the solution.
The first thing we need to do is split the string into an array using the split()
method. If we split on an empty string, the method will give us an array with each individual character in it. We then use that new array to map over.
function reverseString(str) { let newArr = str.split(''); let rev = newArr.map((letter, index, array) => { let swapIndex = array.length - index - 1; return array[swapIndex]; }); return rev.join('') }
Since we are wanting to essentially swap indexes, we need to figure out the index of the character we want to put in the current index’s place. That will be the character we return.
To do that, we find the length of the array, minus one because we are a zero-based array, and then take away the position of the current index. The array[swapIndex] we return essentially takes the place of the current index. This gives us an array of reversed characters in a string.
The final thing we need to do is join the array together into a string and return it.
Test out the solution in the code editor!
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="" /> <script> function reverseString(str) { let newArr = str.split(''); let rev = newArr.map((letter, index, array) => { let newIndex = array.length - index - 1; return array[newIndex]; }); return rev.join('') } function showInput(e) { e.preventDefault(); const inputStr = document.getElementById('user_input').value; if(inputStr.length < 1) { alert("Must enter a string to reverse. Try again.") } let reversed = reverseString(inputStr); document.getElementById( 'display' ).innerHTML = reversed; document.getElementById('user_input').value = ''; } </script> <style> * { box-sizing: border-box;; } body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } #user_input { width: 100%; } #submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } #display { font-size: 1.4rem; height: 50px; } </style> </head> <body> <div> <form onsubmit="showInput(event);"> <label id="label">Enter a String to Reverse:</label> <input type="text" name="message" id="user_input"/> <input type="submit" onclick="showInput(event);" id="submit_button"/><br /> <label>Your input: </label> <p><span id="display"></span></p> </form> </div> </body> </html>
The big thing to remember is that map returns a new array – so we are not modifying the original str/array passed in.
Solution #3: Built-in JavaScript Method
This method of solving this code challenge uses the built in functions/methods split()
, reverse()
, and join()
to solve it in this one-liner:
function reverseString(str) { return str.split('').reverse().join(''); }
Try running the code below and testing it out for yourself to see it work!
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="" /> <script> function reverseString(str) { return str.split('').reverse().join(''); } function showInput(e) { e.preventDefault(); const inputStr = document.getElementById('user_input').value; if(inputStr.length < 1) { alert("Must enter a string to reverse. Try again.") } let reversed = reverseString(inputStr); document.getElementById( 'display' ).innerHTML = reversed; document.getElementById('user_input').value = ''; } </script> <style> * { box-sizing: border-box;; } body { width: 100%; max-width: 500px; height: 100vh; background: lightblue; margin: 0 auto; display: flex; flex-flow: column wrap; align-items: center; justify-content: center; } div { display: flex; flex-flow: column wrap; align-items: flex-start; width: 100%; } form { display: flex; flex-flow: column wrap; width: 100%; background: lightgray; padding: 20px; border: 5px double slategray; } #user_input { width: 100%; } #submit_button { width: 25%; align-self: flex-end; margin-top: 10px; } #display { font-size: 1.4rem; height: 50px; } </style> </head> <body> <div> <form onsubmit="showInput(event);"> <label id="label">Enter a String to Reverse:</label> <input type="text" name="message" id="user_input"/> <input type="submit" onclick="showInput(event);" id="submit_button"/><br /> <label>Your input: </label> <p><span id="display"></span></p> </form> </div> </body> </html>
Essentially what the built-in reverse()
method does is the map()
method (the method we outlined in our previous solution) under the hood; however, it mutates the original array instead of returning a new one since it reverses in place. If you are solving a bigger problem, you may need to create a copy of the original array so you can still access the original if needed.
These are not the only definitive ways to solve this problem – these are just some of the more popular ways to solve it. Experiment and see if you can find other solutions for yourself in the code editor above. Just edit the reverseString()
function and nothing else if you would like to see it on screen.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.