String Reversal In Javascript
There are a bunch of ways to reverse a string in Javascript.
I’ve got a big mug of coffee next to me while writing this and it’s inspiring me. Let’s reverse the string, “coffee”. Here’s how to do it with magical built-in methods:
"coffee".split("").reverse.join("");// "eeffoc"
Let’s break that down.
The #split method turns a string into an array.
"coffee".split(); // ["coffee"]
In order to reverse each letter in the string, we have to pass #split an empty string argument (“”). This splits the string between each character.
"coffee".split(""); // ["c", "o", "f", "f", "e", "e"]
We can then chain the #reverse method and that will reverse all of the elements in the array.
"coffee".split("").reverse(); // ["e", "e", "f", "f", "o", "c"]
Now the string is reversed but it’s still an array. How can we return a string? The #join method will turn an array into a string, so we’ll add that to the end of our method chain.
Similar to #split we need to pass in an empty string argument to #join so our array elements will be joined in-between characters.
// join without argument"coffee".split("").reverse().join(); // "e,e,f,f,o,c"// join with empty string argument"coffee".split("").reverse().join(""); // "eeffoc"
Awesome! Our string is reversed! In an interview setting, you might be asked to reverse a string without using built-in methods. Let’s solve that problem next.
Here’s our reverse function. I’ve included a reversedString variable that we’ll return at the end.
function reverse(str) { let reversedString = ""; return reversedString;}
Now we need to iterate over our string. I like the JS for/of
statement because it’s short and readable.
function reverse(str) { let reversedString = ""; // create variable char that will be assigned the value of each
// element in the string for(let char of str) { // do stuff } return reversedString;}
Inside of our loop, we can concatenate to reversedString by adding char to the front.
reversedString = char + reversedString;
Keeping up with our string being “coffee”, the first time through our loop char = “c”, the next time char = “o”, and so on.
str = "coffee";
reversedChar = "";-------------------
First Time Through:
-------------------for(let char of str) { // char = c
reversedString = char + reversedString;
// now reversedString = "c"}--------------------
Second Time Through:
--------------------for(let char of str) { // char = "o", reversedString = "c"
reversedString = char + reversedString; // now reversedString = "oc"}
When the loop exits our reversedString will be built and we return it at the end of the function. Here’s the whole thing put together.
function reverse(str) { let reversedString = ""; for(let char of str) { reversedString = char + reversedString; } return reversedString;}
It even works with spaces!
reverse("this blog post is over")// "revo si tsop golb siht"
Thanks for reading!