📅  最后修改于: 2023-12-03 15:05:23.208000             🧑  作者: Mango
The reverse()
method is a built-in method of the JavaScript String
object. This method is used to reverse the order of the characters in a string.
str.reverse()
This method does not accept any parameters.
The reverse()
method returns a new string with the characters in reverse order.
reverse()
methodlet str = "hello";
let reversedStr = str.reverse(); // "olleh"
console.log(reversedStr);
In the above example, we have created a string str
and initialized it with the value hello
. Then, we have called the reverse()
method on the str
object and stored the reversed string in a variable reversedStr
. Finally, we have printed the reversedStr
variable to the console.
split()
and reverse()
methodslet str = "hello";
let splitStr = str.split(""); // ["h", "e", "l", "l", "o"]
let reversedStr = splitStr.reverse(); // ["o", "l", "l", "e", "h"]
let joinStr = reversedStr.join(""); // "olleh"
console.log(joinStr);
In the above example, we have created a string str
and initialized it with the value hello
. Then, we have split the str
string into an array of individual characters using the split()
method and stored it in the splitStr
variable. We have used the reverse()
method to reverse the order of the array elements and stored the reversed array in the reversedStr
variable. Finally, we have joined the reversed array elements to form a reversed string using the join()
method and stored it in the joinStr
variable. We have printed the joinStr
variable to the console.
The reverse()
method is supported in all major browsers including Chrome, Firefox, Safari, Edge and Internet Explorer. However, you may need to provide a polyfill for older versions of Internet Explorer.
The reverse()
method in JavaScript can be used to reverse the order of characters in a string. It is a convenient method that can be used to quickly manipulate strings in an application.