Reverse a String in JavaScript

Hey guys, in this example we will learn how to reverse string. There are many different ways to reverse a string, here we are using some of JavaScript built-in reverse function to perform the task.


Reverse a String With Built-In JavaScript Functions:


function reverseString(str) {

    // 1. Use the split() method to split string into array of characters 
    let split_string = str.split('');
    // ["h", "a", "r", "d", "i", "k"] 

    // 2. Use the reverse() method to reverse the array of characters   
    let reverse_string = split_string.reverse();
    // ["k", "i", "d", "r", "a", "h"]

    // 3. Use the join() method to join all characters of the array   
    let join_string = reverse_string.join('');
    // ["k", "i", "d", "r", "a", "h"]

    return join_string;
}

console.log(reverseString('hardik'));
    

Output:

kidrah

Chaining all methods:


// Chaining All methods
function reverseString(str) {
    return str.split('').reverse().join('');
}

console.log(reverseString('hardik'));
        

Post a Comment

1 Comments

  1. Although this "Casioak" G-Shock might link seem a radical departure link from his other watches, it still ticks a lot of the same boxes. As G-Shocks go, it's a slim, elegant design and has the same subtle but definite geometry as his other pieces. Curtis says it's link also proof that no one's immune to Instagram.

    ReplyDelete