Reverse a String in JavaScript

In this article, we will learn how to reverse a String in JavaScipt with an example.

Basically, we are going to learn different ways to reverse a String in JavaScipt.

Reverse String in JavaScript Example

Here are the three ways to reverse a String in JavaScript:

  1. With built-in functions
  2. With a for loop
  3. With recursion

main.js

Let's create a main.js file and add the following code to it:

// 1. With built-in functions

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

console.log(reverseString("Source code examples"));

// 2. With a for loop

function reverseStringUsingLoop(str) {
  var newString = '';
  for (var i = str.length - 1; i >= 0; i--) {
      newString += str[i];
  }
  return newString;
}

// 3. With recursion

function reverseStringusingRecursion(str) {
  return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}

Note that the comments in the above code are self-descriptive.

index.html

To test JavaScript code, let's create an HTML file named index.html and add the following code to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

Note that we have included the main.js file as an external JavaScript file:

<script src="main.js"></script>

Run index.html in Browser

Run above index.html file in browser and open dev tools -> console to see the output of the JavaScript code:

selpmaxe edoc ecruoS
selpmaxe edoc ecruoS
selpmaxe edoc ecruoS

Related JavaScript Examples

Comments