How to Reverse a String in JavaScript

Reversing a string isn’t uncommon in development, and fairly popular for entry-level interview questions. With JavaScript, we have many ways to reverse a string. We can use a combination of string’s split() method as well as array’s reverse() and join() methods (since strings are ultimately arrays of characters).

Method 1: Using Built-in Methods to Reverse the String – split(), reverse() and join()

We can use the string’s split() method to create an array of characters from the original string. We can then call the array’s reverse() method to reverse the order of elements in the array. Finally, we can use the join() method to convert the reversed array back into a string:

let str = 'Hello World';
string = [...str ].reverse().join("");

console.log(str ); // "dlroW olleH"

Here, the Spread Syntax is used to split the string into an array and is functionally equivalent to the split() method, which you could also use instead. To understand why they all work together, let’s overview what each function does. split() The split() method returns a new array of strings after splitting a string with the provided separator:

string.split(separator, limit) The separator defines where the string splits into an element in the resulting array. We can define the number of the array element with the limit parameter. When we use the split() method with an empty string, ”, the string will be split on every character. It will come in handy when we convert our string into an array of individual characters.

We’ll also look at a little more complex example of nested if statements, where the condition only applies to specific elements. The syntax for this is shown in Listing 4-20.

[...myVar, 4, 5, 6] // combines myVar array with the given elements
myFunc(...myVar) // Use the myVar's elements as argument to the function

When the spread operator is used with a string, the string is converted into a sequence of characters:

let str = 'hello';
console.log([...str]); // ["h","e","l","l","o"]
console.log(str.split('')); // ["h","e","l","l","o"]
str.reverse()

The reverse() returns a reversed array, in-place. That’s to say – the original array is reversed instead of a copy that’s returned as the result:

//JavaScript
let str = ['a','b','c','d'];
let reversedStr = str.reverse();
console.log(str); // ["d","c","b","a"]
console.log(reversedStr); // ["d","c","b","a"]

You don’t need to declare a new variable, but we frequently do in order to rename the variable name to something more descriptive.

Using a for Loop to Reverse the String

/* With a for loop, we can iterate over each character from the string. Starting from the end of the string to the beginning of the string - we can continuously append the characters to a new string and thus form a reversed string:
*/

const str = 'guitar';
console.log('The original string is: ' + str);
let reversedStr = '';

for (let i = str.length - 1; i >= 0; i--) {
  reversedStr += str[i];
}

console.log('The reversed string is: ' + reversedStr);

Here, we created an empty string, reversedStr, to hold the reversed string. String indices are like array indices, they start at 0. Therefore, we started the loop from one less than the length of the string (picking up the letter r) and loop till our counter goes to 0 (with the letter g).

The reversedStr variable concatenates the elements of the string.

Running the code gives us this output:

The original string is: guitar

The reversed string is: ratiug

function getNumber{
console.log("this is a number");
}

Testing for code block

function getNumber{
console.log("this is a number");
}

Related

How to 10x Your LLM Prompting With DSPy

Tired of spending countless hours tweaking prompts for large...

Google Announces A Cost Effective Gemini Flash

At Google's I/O event, the company unveiled Gemini Flash,...

WordPress vs Strapi: Choosing the Right CMS for Your Needs

With the growing popularity of headless CMS solutions, developers...

JPA vs. JDBC: Comparing the two DB APIs

Introduction The eternal battle rages on between two warring database...

Meta Introduces V-JEPA

The V-JEPA model, proposed by Yann LeCun, is a...

Subscribe to our AI newsletter. Get the latest on news, models, open source and trends.
Don't worry, we won't spam. 😎

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Lusera will use the information you provide on this form to be in touch with you and to provide updates and marketing.