You can reverse a string in JavaScript using various methods. Here's a simple function that accomplishes this task using the built-in split()
, reverse()
, and join()
methods:
function reverseString(str) { // Split the string into an array of characters var characters = str.split(''); // Reverse the array var reversedCharacters = characters.reverse(); // Join the characters back into a string var reversedString = reversedCharacters.join(''); // Return the reversed string return reversedString; } // Example usage: var originalString = "Hello, world!"; var reversedString = reverseString(originalString); console.log(reversedString); // Output: "!dlrow ,olleH"Alternatively, you can use a more concise approach by directly chaining the methods:
function reverseString(str) { return str.split('').reverse().join(''); } // Example usage: var originalString = "Hello, world!"; var reversedString = reverseString(originalString); console.log(reversedString); // Output: "!dlrow ,olleH"