Free Website speed, compliance test free . Slow? We can help! Contact us to optimize your site!

Write a function that takes a string as input and returns the string reversed.

September 17, 2024

Reversing a string is a common interview question for JavaScript developers. Here’s a detailed explanation, including the problem statement, various methods to solve it, and a brief discussion of their time and space complexities.


//string reverse  
Input: "bpthink"  
Output: "knihtpb"
Input: "JavaScript"  
Output: "tpircSavaJ"

In the Javascript we have a few methods to reverse a string

Method:1 Using Built-in Functions


function reverseString(str) {
    return str.split('').reverse().join('');
}

// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
[/code]//built-in functions 

function reverseString(str) {
    return str.split('').reverse().join('');
}

// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"

Code Breakdown:

  1. Convert the string to an array: Use the .split('') method to split the string into an array of characters.
  2. Reverse the array: Use the .reverse() method to reverse the order of the elements in the array.
  3. Join the array back into a string: Use the .join('') method to combine the elements of the array back into a string.

Method:2 Using a For Loop

//Using For Loop 

function reverseString(str) {
    let reversed = '';
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
}

// Test the function
console.log(reverseString("bpthink")); // Output: "knihtpb"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"

Code Breakdown:

  1. Initialize an empty string.
  2. Loop through the input string from the last character to the first character.
  3. Append each character to the new string.

No comments yet.

Leave a Comment

Your email address will not be published. Required fields are marked *

    Hi, I’m Prakash. I build websites and help businesses of all sizes grow. Whether you need guidance, support, or assistance with your online presence, I’m here to assist.

    Reach out anytime with questions or for collaboration. Let’s work together to achieve your business goals!

    support@bpthink.com

Your Digital Vision, Realized.

We specialize in crafting custom websites and mobile apps that drive results.