Reverse a string

Reverse a string

ยท

2 min read

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

  1. Convert string into array using split()
  2. Reverse the array using reverse() on the returned array
  3. Convert the array back to a string using join() on the returned array
  4. 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

  1. Create an empty string called 'reversed'
  2. For each character in the provided string. Take the Character and add it to the start of the 'reversed' string
  3. 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

  1. Split the string into a array
  2. Reduce the string
  3. Return new string
const reverse = (str) => {
  return str.split('').reduce((rev,char)=>char + rev,'')
}
ย