JS Algorithm – Reverse string

Photo: Abu Dhabi, United Arab Emirates

Given a string, return a new string with the reversed

Examples:

reverse(‘hello’) === ‘olleh’
reverse(‘Greetings!’) === ‘!sgniteerG’

Here 3 solutions for this Algorithm:

1 solution:

function reverse(str) {
  // Take the string and convert it into array format ->  [' ', ' ', 
  // 'a', 'b', 'c','d']
  const arr = str.split(''); 

  // Will reverse the array -> ['d', 'c', 'b', 'a', ' ', ' ']
  arr.reverse(); 
  // Will convert the array into a string 'dcba  '
  return arr.join('');
}

// Or return the code just in 1 line
// return str.split('').reverse().join('');

reverse('abcd  ');

Result:

2 Solution:

function reverse(str) {
  let reversed = ''; // const type string declaration

  // Iterates over each character starting from
  // rigth side to left side
  for (let i = str.length - 1; i >= 0; i--) {

    // concatenates each character and save it into reversed variable
    reversed += str[i];
  }

  // Resturn reversed variable
  return reversed;
}


reverse('abcd  ');

Result:

Also we can implement the new format of For loop of ES2015

function reverse(str) {
  let reversed = ''; // const type string declaration

  // For loop of ES2015
  // Iterates over each character
  for (let character of str) {

    // concatenates each character and save it into reversed variable
    reversed = character + reversed;
  }

  // Resturn reversed variable
  return reversed;
}

reverse('abcd  ');

3 Solution:

function reverse(str) {
  // reduce method will go to every character in the string
  // start with empty string then adding
  return str.split('').reduce((reversed, character) => {
    return character + reversed;
  }, '');
}

reverse('abcd  ');

Result:

The character parameter will be each character of the original string:

The reversed parameter Will be concatenating the reverse string, starting as empty string:

At this point “return character + reversed;” will be

“a” + “” = “a”

“b” + “a” = “ba”

“c” + “ba” = “cba”

“d” + “cba” = “dcba “

” ” + “dcba” = ” dcba”

” ” + ” dcba” = ” dcba”

Result —–> ” dcba”

By Cristina Rojas.