DEV Community

loading...

How to Reverse a Given String in Javascript

yongliang24 profile image Yong Liang ・1 min read

Objective

Create a function which takes a string as argument and return a reversed version of that string.

Method 1

1.Convert the string into an array so that we can iterate through each character.

2.Iterate the array backward and push each character into a new array. We can use the built-in reverse() function or write one ourselves.

3.Finally use .join() to convert the array back to a string and return it.

//This solution uses all javascript built-in methods

function reverseString(str){

    let strArray = str.split("") 
    //it's important not to add space on the quotation mark here.

    strArray = strArray.reverse()

    return strArray.join("") //also no space on quotation mark here
}

reverseString("amazon google") //call the function

"elgoog nozama" //the returned string

Write our own reverse method:

function reverseString(str){

    let revArray = [];
    let strArray = str.split("")

    // Looping from the end to the beginning
    for(let i = strArray.length; i >= 0; i--) {

       //push each character into the new array
        revArray.push(strArray[i]); 
    } 

    // Joining the array elements 
    return revArray.join(''); 
}

Instead of using the built-in .split() to converse a string to array, We can also use the for ... of loop. This way we can iterate through each character of a string instead of an array.

function stackReverse(str){
    let strArray = [];

    for(let eachLetter of str){
        strArray.push(eachLetter)
    }

    strArray.reverse();

    return strArray.join("")

}

stackReverse("google amazon") //call the function

"nozama elgoog" //return value

This is my finding for how to reverse a string in javascript, hope you've enjoyed it.

Discussion (2)

pic
Editor guide
Collapse
anduser96 profile image
Andrei Gatej

Thanks for sharing!

Here’s my favorite way to reverse a string:

const len = str.length;
for ( let i = 0; i < Math.floor(len / 2); i++) {
  let temp = str[i];
  str[i] = str[len - i - 1];
  str[len - i - 1] = temp;
 }
Collapse
moresaltmorelemon profile image
Ezra Schwepker

Why not use all array methods?

const reverseStr = str => str.split('').reverse().join('');