Using a function to reverse a given string.
Expected results:
reverse('apple') // 'elppa
reverse('hello') // 'olleh'
reverse('Learning To Code!') //'!edoC oT gninraeL'
Solution 1 - Built in functions
- Convert string into array using split()
- Reverse the array using reverse() on the returned array
- Convert the array back to a string using join() on the returned array
- Return the new reversed string
const reverse = (str) => {
// split string
const split = str.split('') //['a','p','p','l','e']
//reverse array
const reverse = split.reverse() //['e'.'l','p','p','a']
//convert array back to string
const newString = reverse.join('') //elppa
// return new string
return newString //elppa
}
Chaining the methods together:
const reverse = (str) =>{
return str.split('').reverse().join('');
}
Solution 2 - For loop
- Create an empty string called 'reversed'
- For each character in the provided string. Take the Character and add it to the start of the 'reversed' string
- Return the variable 'reversed'
const reverse = (str) =>{
//declare variable
let reversed= ''
//loop through the string
for(let char of str){
reversed= char + reversed
}
//return new string
return reversed
}
/*
/ reversed variable after each loop
''
'a'
'pa'
'ppa'
'lppa'
'elppa'
*/
Solution 3 - Array reducer helper
- Split the string into a array
- Reduce the string
- Return new string
const reverse = (str) => {
return str.split('').reduce((rev,char)=>char + rev,'')
}
ย