RunJS LogoRunJS

Reverse a String in JavaScript: 3 Expert Methods You Should Know

Published on

reverse a string in javascript

A common task in JavaScript is to reverse a string. Knowing how to reverse a string in JavaScript can help developers improve their coding skills and make them more efficient.

In this post, you will learn 3 expert methods to reverse a string in JavaScript. We will start with the built-in methods like split(), reverse(), and join(), which are easy to implement.

Then we move on to using loops and recursion, which are more complex but can offer be useful in some situations.

We will also cover how to reverse a palindrome string and combine multiple methods to achieve our goal efficiently.

By the end of this guide, you will have powerful knowledge to handle any string reversal task that comes your way.

Reverse a string in JavaScript with split, reverse, and join methods:

Let me break down what each method does so you can understand how these built-in JavaScript methods can help us in string reversal.

split()

You can use split() to turn a string into an array of words or characters. It accepts two parameters:

  • Separator: The string will be divided into substrings wherever the separator occurs. It could be space, a single character, a comma, or a regular expression.
  • Limit (optional): It sets the maximum limit of string reversal. After that, the remaining part of the string doesn't split. The default behavior is to split the entire string.

Example:

Calculate the words of the meta description by using the split method.

const description = "JavaScript in a nutshell";
// Turns the text into an array of words
const words = description.split(" ");
words; // [ 'JavaScript', 'in', 'a', 'nutshell' ]
words.length; // 4

reverse()

Use reverse() to reverse the order of the elements in an array. It doesn't support any parameters.

Example:

With split(), you learned about turning the meta description string into a words array.

Now, reverse the order of array elements using the reverse() array method.

const words = ["JavaScript", "in", "a", "nutshell"];
words.reverse();

join()

Use join() to turn an array's elements into a string. It accepts one optional parameter:

  • Separator(optional): It inserts the desired character or string between each pair of adjacent elements. By default, the value of the separator in join() is a comma (,).

Example:

In reverse(), you learned about elements reversal in an array. Turn that reversed array into a string using the join() array method.

const reversedWords = ["nutshell", "a", "in", "JavaScript"];
reversedWords.join(); // 'nutshell,a,in,JavaScript'
reversedWords.join(" "); // 'nutshell a in JavaScript'

How can we use split, reverse & join in reversing a complete string instead of words?

Just modify the split() separator.

Here is a complete code snippet :

const description = "JavaScript in a nutshell";
// Turns the text into an array of characters
const words = description.split("");
// reverse the array elements
words.reverse();
// Turns the reversed array of elements into a string
words.join("");

Reusable function to reverse a string in JavaScript:

By using spit, reverse, and join methods. Let's create a reusable function to reverse a string in JavaScript.

const description = "JavaScript in a nutshell";
const reverseString = (str) => {
return str.split("").reverse().join("");
};
reverseString(description);

With RunJS, you can store reusable code with the code snippets feature.

Select the piece of code you want to store and right-click to create a code snippet for future use.

create code snippet

Name and put a little description about the usage of the code snippet:

name code snippet

Access your saved code snippets instantly by typing the name:

access code snippet

Reverse a string using a for loop:

Is it possible to do string reversal without using any built-in JavaScript methods?

Yes, let's do it by using a for loop:

First, understand that you can access a character by using the array format:

const text = "Hey RunJS";
text[0]; // H
text[4]; // R

Here is a quick code snippet:

const str = "JavaScript in a nutshell";
let reversedStr = "";
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}

Breakdown:

  • An empty string is stored inside reversedStr to avoid undefined.
  • str.length returning the length of the string. In our case length is 28.
  • Since the index starts from zero, we need to subtract 1 from the length to start the reverse loop from the right index (27).
  • Every single time when the loop runs, reversedStr will get a character or a space starting from the end.
  • reversedStr += str[i] tells to store and concatenate a string.
  • First Run: reversedStr += str[27] => l will append to reversedStr (l)
  • Second Run: reversedStr += str[26] => l will append to reversedStr (ll)
  • Third Run: reversedStr += str[25] => e will append to reversedStr (lle)
  • And So on, this is how it will output a complete reversal of "JavaScript in a nutshell" string => "'llehstun a ni tpircSavaJ'"

Reverse a string in JavaScript using recursion:

The recursive method shows how a function can use self-calling to reverse a string.

It achieves this by breaking the string into smaller substrings and constructing the reversed string through recurring calls.

function reverseString(str) {
if (!str) return "";
return reverseString(str.substring(1)) + str.charAt(0);
}
const str = "JavaScript in a nutshell";
const reversedString = reverseString(str);
// Output: llehstun a ni tpircSavaJ

substring():

You can use substring() to extract a portion of a string. substring has two paramters:

  • start: Specifies the position within the string where the extraction should begin. If the start parameter is greater than or equal to the length of the string, an empty string is returned.
  • end(optional): Determines the index position where the extraction should stop (not inclusive). Note: If you're using substr (stop using it, as is is now deprecated). Start using the substring() method instead.

substring in javascript

charAt():

This is used for retrieving the character at a specific index position within a string. It accepts one parameter.

  • index: Specifies the character's position to retrieve from the string. If the index is less than 0 or greater than or equal to the length of the string, an empty string is returned.

charat in javascript

Here is an example of charAt() being used in a recursive revserse string function:

function reverseString(str) {
if (str === "") {
return "";
} else {
return reverseString(str.substring(1)) + str.charAt(0);
}
}
const str = "JavaScript in a nutshell";
const reversedStr = reverseString(str);
console.log(reversedStr);

Let me break it down:

  • Start with the provided string str assigned to "JavaScript in a nutshell"
  • Call the reverseString function and pass str as an argument.
  • Check if the input string str is an empty string ("") using the condition str === ""
  • Since the string is not empty, proceed to the else block.
  • Call reverseString recursively with str.substring(1) as the argument. It extracts a substring starting from the second character of str.
  • Concatenate the result of the recursive call with str.charAt(0), which retrieves the first character of str.
  • The recursive call continues until it reaches the base case of an empty string.
  • When the process of calling itself stops, and the basic condition is met, you will get the final reversed string.
  • Assign the reversed string to the variable reversedStr.
  • Print the value of reversedStr to the console.

Quick challenge: Reverse palindrome string in JavaScript

A palindrome is something that reads the same way forward and backward. It doesn't change when its order is reversed.

Do you have your solution?

Here is my solution using built-in JavaScript methods:

function isPalindrome(str) {
// Reverse the string
const reversedStr = str.split("").reverse().join("");
// Compare the main string with its reversed version
return str === reversedStr;
}
const word = "level";
const result = isPalindrome(word);
console.log(result); // Output: true

Frequently asked questions

Are there any limitations or potential issues with certain string reversal methods?

There can be limitations and potential issues like character encoding, multibyte, Unicode characters, and performance. For example, using split, reverse, and join creates an array from the string, reverses the array, and then joins it back into a string, which can be inefficient for large strings.

What is the fastest way to reverse a string JavaScript?

The fastest way to reverse a string in JavaScript is by using a loop to iterate through the characters in reverse order and build the reversed string by appending each character. This approach avoids unnecessary array operations and performs optimally for string reversal.

Conclusion

In conclusion, mastering string reversal in JavaScript is useful for efficient coding.

To achieve this task, you learned various methods, including built-in functions, recursion, and loops.

For further JavaScript experimentation and learning, try using RunJS, a JavaScript playground that allows you to test and refine your code instantly without using a browser.

TwitterShareFacebookShareLinkedInShareRedditShareY CombinatorShare

Join the RunJS mailing list

You'll receive an occasional newsletter with development updates and articles from the blog. Unsubscribe at any time.

Recent posts