These solutions are from JavaScript Notes for Professionals.

Solution 1


function reverseString(str) {
 return str.split('').reverse().join('');
}
reverseString('hello'); 

// "olleh"

Note: The above solution only works if does not contain surrogate pairs.

Solution 2: Using Spread operator


function reverseString(str) {
 return [...String(str)].reverse().join('');
}

console.log(reverseString('hello')); // "olleh"

Solution 3: Make a function using a For loop


function reverse(string) {
 var strRev = "";
 for (var i = string.length - 1; i >= 0; i--) {
 strRev += string[i];
 }
 return strRev;
}
reverse("hello"); // "olleh"

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *