Answered
How can I reverse a string in JavaScript?
For example, a given string of example
should be converted into elpmaxe
as the end result.
Is there a function or method that does this easily?
This will reverse your string:
string.split("").reverse().join("");
Code breakdown:
split("")
: converts the string into an array containing each letter in the word. i.e. ["e", "x", "a", "m", "p", "l", "e"]
.reverse()
: reverses the order of the array.Here's how you could do it with a decrementing for
loop:
let ogString = "example";
let newString = "";
for (var i = ogString.length - 1; i >= 0; i--) {
newString += ogString[i];
}
// newString = "elpmaxe"
function reverseString(string){
return [...string].reverse().join("");
}
Using the reverse()
method:
string.split("").reduce((rev, char) => char + rev, "");
Loop through each character in the string:
function reverse(string) {
let reversed = "";
for (let character of string) {
reversed = character + reversed;
}
return reversed;
}