CodeBox CodeBox

JavaScript Reverse String

Typescript / JS
けい

1. 🧐 Expected Output

reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'


2. 🤔 My Solution

  • Call 'charAt' method to get a specified index in a string
  • Call 'push' method on the 'result' array
  • Join 'result' array and call 'replaceAll' method
function reverse(str) {
  const lastIndex = str.length - 1
  const result = []

  for (let index = 0; index <= lastIndex; index++) {
    let targetStr = str.charAt(index)
    const reversedIndex = lastIndex - index

    targetStr = str.charAt(reversedIndex)
    result.push(targetStr)
  }

  const convertedResult = result.join().replaceAll(",","")
  return convertedResult
}


3. 🎊 Best Solution

3-1. First possible solution

  • Turn 'str' into an array with 'split' method
  • Call 'reverse' method on the array
  • Join the array, Back into a string
function reverse(str) {
  const arr = str.split('')
  arr.reverse()
  return arr.join('')
}


3-2. Second possible solution

  • Iterate through all of the characters of 'str' with for loop
function reverse(str) {
  let reversed = ''

  for (let character of str) {
    reversed = character + reversed
    console.log(reversed)
  }

  return reversed
}


3-3. Last possible solution

  • Call 'reduce' method
  • 'reversed', which is first argument of reduce method is the initial value, or the previously returned value of the function
  • 'character', which is second argument of reduce method is the value of the current element.
function reverse(str) {
  return str.split('').reduce((reversed, character) => {
    return character + reversed
  },'')
}

ABOUT ME

けい
ベンチャーのフロントエンジニア。 主にVueとTypescriptを使っています。ライターのための文字数カウントアプリ:https://easy-count.vercel.app/