DEV Community

Uyai-Abasi
Uyai-Abasi

Posted on

How to Reverse string in JavaScript

Hello and welcome to my first article! As a tech newbie myself, I understand how daunting it can be to dive into the world of technology. But fear not! This article is designed to provide you with a basic introduction to the topic at hand, and I hope it will help you gain a better understanding of the subject.

So sit back, relax, and get ready to learn something new. Let's dive into the fascinating world of technology together!

In programming, string manipulation is a common task that is required to achieve various objectives. One such task is to reverse a string. A string reversal means to change the order of the characters in a string. For instance, reversing the string "Hello" will give "olleH". In this article, we will discuss how to reverse a string in JavaScript.

There are several ways to reverse a string in JavaScript. We will discuss some of the most commonly used methods below.

  1. Using the split(), reverse(), and join() methods This is the most commonly used method to reverse a string in JavaScript. It involves splitting the string into an array of characters, reversing the array, and then joining the array back into a string. Here's how to do it:
const str = "Hello";
const reversedStr = str.split("").reverse().join("");

console.log(reversedStr);
Enter fullscreen mode Exit fullscreen mode

The split() method splits the string into an array of characters, the reverse() method reverses the order of the elements in the array, and the join() method joins the elements of the array back into a string.

  1. Using a for loop

Another way to reverse a string is to use a for loop. This method involves iterating through the string from the last character to the first character and concatenating the characters into a new string.

Here's how to do it:

const str = "Hello";
let reversedStr = "";
for (let i = str.length - 1; i >= 0; i--) {
  reversedStr += str[i];
}
console.log(reversedStr);
Enter fullscreen mode Exit fullscreen mode

This method initializes an empty string and then iterates through the original string from the last character to the first character using a for loop. In each iteration, the current character is concatenated to the new string.

  1. Using recursion

Another way to reverse a string is to use recursion. This method involves calling a function recursively to reverse the string.

Here's how to do it:

function reverseString(str) {
  if (str === "") {
    return "";
  } else {
    return reverseString(str.substr(1)) + str.charAt(0);
  }
}
console.log(reverseString("Hello"));
Enter fullscreen mode Exit fullscreen mode

This method checks if the string is empty. If it is, it returns an empty string. If it is not empty, it calls the function recursively with the substring starting from the second character and concatenates the first character to the end.

In conclusion, there are several ways to reverse a string in JavaScript. The most commonly used method involves using the split(), reverse(), and join() methods. Other methods include using a for loop and recursion. Each method has its advantages and disadvantages, and the best method to use depends on the specific requirements of the project.

Thank you for reading to this point, I hope this was helpful in some way.

Top comments (11)

Collapse
 
hakki profile image
Hakki • Edited

Using split('') might not work well with Unicode characters, especially with characters outside the Basic Multilingual Plane (BMP). To properly handle Unicode characters, you can use the Array.from() method to create an array of characters while preserving the Unicode characters.

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

Collapse
 
peerreynders profile image
peerreynders

It returns an iterator that yields the Unicode code points of the string value as individual strings.

To reverse a unicode string you need an iterator over the grapheme clusters.

String.prototype[@@iterator]() - JavaScript | MDN

The @@iterator method of a string implements the iterable protocol and allows strings to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an iterator that yields the Unicode code points of the string value as individual strings.

favicon developer.mozilla.org
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Using :str.split('') does not work at all well with Unicode characters. [...str] is much better, but still not perfect.

Collapse
 
peerreynders profile image
peerreynders • Edited
import ReverseString from "./reverse-string"

// …

it('emoji grapheme clusters', () => {
    // multi-codepoint grapheme clusters
    const emojis =   [
      '\uD83C\uDF37',
      '\uD83C\uDF81',
      '\uD83D\uDCA9',
      '\uD83D\uDE1C',
      '\uD83D\uDC4D',
      '\uD83C\uDFF3\uFE0F\u200d\uD83C\uDF08'
    ];
    const input = emojis.join('');
    const expected = emojis.reverse().join('');
    expect(ReverseString.reverse(input)).toEqual(expected);
  })
Enter fullscreen mode Exit fullscreen mode

grapheme-splitter

Intl.Segmenter - JavaScript | MDN

The Intl.Segmenter object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.

favicon developer.mozilla.org

String - JavaScript | MDN

The String object is used to represent and manipulate a sequence of characters.

favicon developer.mozilla.org
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Yup, I was too tired to go into these last night πŸ‘

Collapse
 
polaroidkidd profile image
Daniel Einars

Awesome API! Shame it's missing in FF

Thread Thread
 
peerreynders profile image
peerreynders

It only became part of the Internationalization API Specification (ECMA 402) with ES2022.

bugzilla.mozilla.org/show_bug.cgi?...

Collapse
 
przemyslawjanbeigert profile image
Przemyslaw Jan Beigert

write your snippet like "

javascript" instead of just "

". It's hard to read without syntax colors.

Collapse
 
hethinksthrice profile image
ATLIEN.

Thank you.

Collapse
 
usenmfon_uko profile image
Usenmfon

This is awesome!

Collapse
 
justin__mark profile image
Justin

Super helpful!