reverse algorithm using javascript code example
Example 1: javascript string reverse
"this is a test string".split("").reverse().join("");
//"gnirts tset a si siht"
// Or
const reverse = str => [...str].reverse().join('');
// Or
const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, '');
// Or
const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`;
// Example
reverse('hello world'); // 'dlrow olleh'
Example 2: javascript how to reverse a string
function reverseString(str) {
// Step 1. Use the split() method to return a new array
var splitString = str.split(""); // var splitString = "hello".split("");
// ["h", "e", "l", "l", "o"]
// Step 2. Use the reverse() method to reverse the new created array
var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
// ["o", "l", "l", "e", "h"]
// Step 3. Use the join() method to join all elements of the array into a string
var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
// "olleh"
//Step 4. Return the reversed string
return joinArray; // "olleh"
}
reverseString("hello");