JavaScript(JS) JS reverse a string
www.ifigtidea.com
To reverse a string in JavaScript, you can use the split()
and reverse()
methods to convert the string to an array, reverse the array, and then join the array back into a string. Here's an example:
let str = "hello world"; let newStr = str.split("").reverse().join(""); console.log(newStr); // Output: "dlrow olleh"
In this code, we define a string str
that we want to reverse. We use the split()
method with an empty string as the separator to convert the string to an array of individual characters. We then use the reverse()
method to reverse the order of the array elements. Finally, we use the join()
method with an empty string as the separator to join the array back into a string.
The resulting newStr
variable contains the reversed string, which we print to the console using console.log()
. The output should be the original string reversed.