Anurag Sinha
TechnCode

TechnCode

Reverse a String - using JavaScript

Anurag Sinha's photo
Anurag Sinha
·Nov 24, 2021·

2 min read

Reverse a String - using JavaScript

Table of contents

Introduction

  • The Data Structures and Algorithms Practice series starts with a very simple yet famous question, i.e. - Reverse a String.

  • I would primarily be using JavaScript as a programming language for this series. Implementations via C#, Java will be thought of as of later.

Problem Statement

Reverse a input string

Ex: Hello World -> dlroW olleH

Implementations

1) Using For Loop:

We run the for loop in backwards direction - starting from the last character of the string.

//using for loop
function reverseString(str) {
  let result = "";
  for (let i = str.length - 1; i >= 0; i--) {
    result = result + str[i];
  }
  return result;
}

console.log(reverseString("Brown Fox"));
console.log(reverseString("Hello World 1 !!!"));

image.png

2) Using for of loop:

//using for-of loop
function reverseUsingForOfLoop(str) {
  let result = "";
  for (let item of str) {
    result = item + result;
  }
  return result;
}

console.log(reverseUsingForOfLoop("Black Fox"));
console.log(reverseUsingForOfLoop("Hello World 2 !!!"));

image.png

3) Using reverse() method on string array:

We would convert the input string into an array -> apply reverse() method on the array -> join the array back to the reversed string.

function reverseStringUsingReverse(str) {
  return str.split("").reverse().join("");
}

console.log(reverseStringUsingReverse("Blue Fox"));
console.log(reverseStringUsingReverse("Hello World 3 !!!"));

image.png

4) Using reduce() method

We would convert the string to an array and feed the array to the reduce method in order to reverse it.

//using reduce method to reverse a string
function reverseUsingReduce(str) {
  return str.split("").reduce((rev, item) => item + rev, "");
}
console.log(reverseUsingReduce("Red Fox"));
console.log(reverseUsingReduce("Hello World 4 !!!"));

image.png

The full code is present in the Github repo : github.com/anurag1302/dsalgo-javascript
 
Share this