reverse a string in Javascript
Code snippet on how to reverse a string in Javascript
function reverseString(str) {
let reversedStr = '';
for (var i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
This code takes a string as its argument (e.g. ‘hello’) and reverses the word. The first line creates an empty string (reversedStr
) which will be used to store the reversed string. The second line uses a loop, starting from the end of the string, to add each character of the original string to the reversedStr
. Finally, the reversed string is returned.