Reverse a string
Given a string, reverse the string, in other words reverse the order of characters in the string, using JavaScript.
Solution
There is no direct method to reverse a string in JavaScript. So, we make a work around using arrays.
To reverse a given string using JavaScript, first split the string into character array, reverse the array, and join the array.
String.split("")
splits the string into array of characters. Observe that we passed an empty string as argument to split() method.
Array.reverse()
reverse the array of characters.
Array.join("")
joins the array of characters into a string. Again, observe that we have passed an empty string to join() method. Empty string is used as delimiter between the items of the array while joining.
All these methods can be joining together via chaining mechanism. The string str
can be reversed using the following expression.
str.split("").reverse().join("")
Program
1. Given a string in str
. Reverse the string str
.
let str = 'Hello World';
let output = str.split("").reverse().join("");
console.log(output);