Problem Statement:
Write a JavaScript function to reverse a given string.
Solution:
We take an input string and split it into an array of characters using split(“”).
We reverse the array using reverse().
Finally, we join the reversed array back into a string using join(“”).
Solution Explanation:
- The
split("")
method converts the string into an array of characters. - The
reverse()
method reverses the array. - The
join("")
method converts the array back into a string.
Solution:
function reverseString(str) {
return str.split(“”).reverse().join(“”);
}
console.log(reverseString(“hello”)); // Output: “olleh”
Example Output:
Input: “hello”
Output: “olleh”