To reverse a string, you can split the string into an array of characters, reverse the array, and then join the characters back into a string.
- Convert the string into an array of characters.
- Use the
reverse()
method to reverse the array. - Join the array back into a string using the
join()
method. - Return the reversed string.
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example usage
console.log(reverseString("hello")); // Output: "olleh"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
This method has a time complexity of O(n), where n is the length of the string.
Tags: basic, JavaScript, Strings, Algorithm