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 , ''));

}

 

 

Advertisements

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s