Photo by Hunter James on Unsplash
In this article, we will learn about the three possible ways to reverse a string in JavaScript.
1) Using reverse
- In the following code example, we are splitting the given input string into an array of characters. Then reverse the array of characters and joining the individual characters into a string using the join() method. Finally, will get a reversed string.
const reverseString = str => {
return [...str].reverse().join('');
};
reverseString("JavaScript");
Output
tpircSavaJ
2) Using unshift
- In the following code example, we are splitting the given input string into an array of characters. Then iterating each character one by one and pushing it as the first item of an array. Finally, joining the new array of characters into a string using the join() method and can get a reversed string.
const reverseString = str => {
const reversedStr = [];
[...str].forEach(item => reversedStr.unshift(item));
return reversedStr.join('');
};
reverseString("React");
Output
tcaeR
3) Using push
- In the following code example, we are splitting the given input string into an array of characters. Then iterating each character one by one and pushing it into an array based on their index position. Finally, joining the new array of characters into a string using the join() method and will get a reversed string.
const reverseString = str => {
const reversedStr = [];
[...str].forEach((item, index) => reversedStr.push([str.length - (index + 1)]));
return reversedStr.join('');
};
reverseString("Angular");
Output
ralugnA
Hint to the methods used in the above code examples.
reverse() is the default method to reverse an array.
push() method is adds a new item to the begining of an array.
unshift() method is adds a new item to the end of an array.
forEach() method calls a function for each element in an array, in order.
spread operator (…) is used to expand or spread an iterable or an array.
That’s all about this blog post friends. Share your ideas on this topic. Will learn something new in our next post.