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

0 Comments