How to reverse a string in JavaScript
In this tutorial, we will learn how to reverse a string in JavaScript.
Reversing a string in JavaScript
Variables used in the code
str – the name of the variable where we store our string that we are going to reverse later.
let str = "This is a Tutorial in CodeSpeedy"
Method 1
In this method/function I have iterated through the characters in the string str and append each character to the front of the string reverse. I have used the length attribute to get the length of the string. This method is a general approach to reverse the string.
function reverseString(str){ let reverse = "" for(let i=0;i<str.length;i++){ reverse = str[i]+reverse } return reverse }
Method 2
In this method/function I have used inbuilt functions to accomplish our goal. We split the string to get the array of each character using the split() function and we reverse the array using the reverse() function. Finally, we join the reversed character array of the string str by using the join() method.
function reverseString(str){ let charStrings = str.split("") let reverseCharStrings = charStrings.reverse() return reverseCharStrings.join("") }
Here charStrings contains the array of characters in the string str. reverseCharStrings is the array obtained by reversing the charStrings array.
Output
console.log(reverseString(str))
ydeepSedoC ni lairotuT a si sihT
From the output result, you can see we have successfully been able to reverse our string in JavaScript.
Leave a Reply