Reversing a string in 3 ways using JavaScript

There are three popular ways you can reverse a string in JavaScript.

Solution #1Using S-P-J (Split-Reverse-Join)

  • Split the string into array of characters using split() function
  • Reverse the characters of array using reverse() function
  • Join back the characters in the array using join() function

function reverse(str){

return str.split('').reverse().join('');

}

Solution #2 – Using Loop – C-L-A(Create – Loop – Add)

  • Create an empty string
  • Loop through each character in string you want reverse
  • Add it to the empty string

function reverse(str){

var rev = '';

for(var char of str){

rev = char + rev;

}

return rev;

}

Solution #3 Using reduce() function

Read about reduce() function


function reverse(str){

return str.split('').reduce((rev, char) => (rev + char , ''));

}

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s