In JavaScript, you can reverse a string using several methods.
Here are few ways to reverse a string:
Method 1: Using String and Array built-in methods:
One of the easy ways to reverse a string in javascript is using split()
, reverse()
and join()
methods.
For example:
const str = "hello world";
const reversedString = str.split("").reverse().join("");
console.log(reversedString); // Output: "dlrow olleh"
As you can see in the example above, we first split the string into array of characters using the split()
method.
Then, we use the reverse()
method the order of the array elements and finally we join the array elements using the join()
method
to get the reversed string.
Method 2: Using loop:
We can also reverse a string using loop.
const str = "hello world";
let reversedString = "";
for (let i = str.length - 1; i >= 0; i--) {
reversedString += str[i];
}
console.log(reversedString); // Output: "dlrow olleh"
As you can see in the above code snippet, we iterate over the string characters in reverse order using a for loop and concatenate each character to the reversedString
variable.
Method 3: Using the recursion:
We can also reverse a string using the recursion.
Below is code for that:
function reverseString(str) {
if (str === "") {
return "";
} else {
return reverseString(str.substr(1)) + str.charAt(0);
}
}
const str = "hello world";
let reversedString = reverseString(str);
console.log(reversedString); // Output: "dlrow olleh"
In this method, we define a function called reverseString()
that takes a string as an argument. The function uses recursion to reverse the string by calling itself with the substring starting from the second character and concatenating the first character at the end. The recursion continues until the string is empty.
These are just few ways to reverse the string in Javascript.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.