Thursday, November 29, 2018

How to reverse a string in JavaScript

This tutorial explains how to reverse a string in JavaScript. We are using reverse method, reduce method to reverse a string in javascript.

How to reverse a string in JavaScript

Method - 1 :

We used split method to split the string into an array of individual strings then chain it to reverse method.

const str = "ABCDEFGH"

let getReverseString = str.split('').reverse().join('')

console.log(getReverseString)

Output :
-----------------------
> "HGFEDCBA"


Method - 2 :

Reverse a string in traditional way using while loop.

function reverseString(str){

  const arr = [...str]
  let reverse= "";

  while(arr.length){
     reverse = reverse + arr.pop()
  }

  return reverse
}

const stringvalue = "ABCDEFGH"

console.log(reverseString(stringvalue))

Output :
-----------------------
> "HGFEDCBA"


Method - 3 :

Here we spread the string using spread operator and reverse the string using the reduce method.

const str = "ABCDEFGH"

let stringVal = [...str].reduce((prev,next)=>next+prev)

console.log(stringVal)

Output :
-----------------------
> "HGFEDCBA"

This is all about reverse a string in JavaScript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment