How to Reverse a String in JavaScript

JavaScript is a programming language that can be used to make webpages interactive. One common task is reversing strings, and this post will show you how. First, we’ll introduce the reverse() function in JavaScript. Next, we’ll see how to use it on strings with multiple characters. Finally, we’ll give some example code of using the reverse() function on our string JavaScript.

Reverse a String with reverse()

The reverse() method in JavaScript reverses an array. The first element becomes the last, and vice versa with all of the other elements within it until all elements are in opposite spots of their original ones.

The method can reverse an array but what we want to do is to apply it to a string. So, we need to convert a string to an array with split() method.

Steps:

  • Convert a string to an array with split().
  • Reverse all element os the array with reverse().
  • Turn the reversal array into a string again with join().

let reversed_word = "Hello".split('').reverse().join('');
console.log(reversed_word);
//outout: olleH

In the example above, the output is “olleH” for “Hello” input.

Reverse string with loop

We can try a more traditional way by looping a string in reversed order then save each character to a temporary string.

let output = '';
let word = 'This is another example';

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

console.log(output);

The output: “elpmaxe rehtona si sihT”

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close