In the following tutorial, you will learn how to reverse a string in JavaScript in a very simple and practical way by creating some functions that will be very helpful.
First, we will create a custom function that will take a text string as a parameter and should return that string reversed.
Creating the reverseString() function in JavaScript
const string = "Parangaricutirimucuaro";function reverseString(str) {let arrStr = str.split("");return arrStr.reverse().join("");}reverseString(string); // This returns 'oraucumirituciragnaraP'
We declare the string 'Parangaricutirimucuaro' (this is a widely used tongue twister in my country). We create the reverseString function, which takes a string as an argument. Inside the function, we convert the text into an array using the .split("") method. Then, we return the value using the .reverse() method, which reverses the order of the array values. Finally, since we need to return a string, we use the .join("") method to transform the array into a string.
Reversing the text of a string using arrow functions
With the ES6 standard, the reverseString() function can be written more clearly and concisely in a single line of code.
const word = "Parangaricutirimucuaro";const reverseString = str => str.split("").reverse().join("");reverseString(word); // This returns 'oraucumirituciragnaraP'
Reverse string using a for loop
The previous method is simple and efficient; however, another more convoluted and unnecessary approach is as follows:
- Convert the string into an array.
- Declare an empty array where we will add each letter of the string in reverse order.
- Then, we use a traditional for loop, but in this case, the variable 'i' will have the decrement operator (--) to traverse the array in reverse. For each index, we add a new value to the 'arrReverse' array.
- Finally, we convert the array back into a string using the .join() method.
const string = "Parangaricutirimucuaro";function reverseStringFor(str) {let arrStr = str.split("");let arrReverse = [];for (let i = arrStr.length; i >= 0; --i) {arrReverse.push(arrStr[i]);}return arrReverse.join("");}reverseStringFor(string); // this return 'oraucumirituciragnaraP'
I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.
About me