INTRODUCTION
There are many ways you can reverse a string in JavaScript, it include:
- Using for Loop
- Using Recursion
- Using the reduce() method or
- Using split() method in combination with reverse() and join() method
CODE SAMPLE 1 (Using For Loop). Place the code in the body tag of your HTML document
<script>
let siteName="EasyCode"
let reversedName=""
for (let i=siteName.length-1; i>=0; i--){
reversedName+=siteName[i]
}
document.write(reversedName)
</script>
CODE SAMPLE 2 (Using Combination of split(), reverse() and join() method)
<script>
let siteName="EasyCode"
let reversedName=siteName.split("").reverse().join("");
document.write(reversedName)
</script>
EXPLANATION CODE SAMPLE 1
Line 1: Declare a variable called siteName that stores the text "EasyCode"
Line 2: Declare an empty string of variable called reversedName
Line 3: Declare a variable i and assigned it the size of the string -1. Example length of EasyCode is 8. 8-1 is 7. The reason of the subtraction is, the last index of an array is 1 less than the value of the array. We check if the value of i (7 in this case) is greater than or equal to 0.
Line 4: Pick the character at index 7 and concatenate it to the empty string reversedName return the execution to line 3 and decrement the value of i. Repeat line 3 to 4
Line 5: Display the reverse word on the screen.
EXPLANATION CODE SAMPLE 2
To fully understand the code at sample 2. You need to understand what function each of the default functions perform.
- Split function. It split the string to an array. so "EasyCode" becomes ["E", "a", "s", "y", "C", "o", "d", "e"]
- Reverse method. Reverse method does not work directly on string, it only work on array so that was the reason we used the split method first to convert our string to array then apply the reverse method to the array. The output become ["e", "d", "o", "C", "y", "s", "a", "E"]
- The join method join array back to string. It picks the reverse array ["e", "d", "o", "C", "y", "s", "a", "E"] and convert it to the string "edoCysaE"
- The final result is outputted.
TRY IT YOURSELF
Try changing the name of the string that is used to see the output. You can also rewrite the program without seeing to see if you have understand the tutorial.
CONCLUSION
The tutorial taught you how to reverse a string using 2 different approaches from the 4 listed above. Both approach give the same result but the second approach is shorter and does not require much logic.
You can post your comment if you want me to use the other 2 approach
ReplyDelete