OneBite.Dev - Coding blog in a bite size

reverse string in javascript

Code snippet for how to how to reverse string in javascript with sample and detail explanation

Understanding how to manipulate strings is crucial in any programming language, including JavaScript. This article will guide you through how to reverse a string in JavaScript.

Code snippet for reversing a string

Here is an efficient and simple way to reverse a string with JavaScript:

function reverseString(str) {
    return str.split('').reverse().join('');
}
console.log(reverseString("Hello World"));

Code Explanation for reversing a string

Let’s break down each step of the function:

  1. .split(''): This method is used to split a string into an array of substrings. In this case, it splits the string into individual letters.

    • Example: "Hello".split('') will return ['H', 'e', 'l', 'l', 'o'].
  2. .reverse(): This method is used on arrays to reverse their order.

    • Example: ['H', 'e', 'l', 'l', 'o'].reverse() will return ['o', 'l', 'l', 'e', 'H'].
  3. .join(''): This method is used to rejoin the elements in the array back into a single string.

    • Example: ['o', 'l', 'l', 'e', 'H'].join('') will return 'olleH'.

In the function reverseString(str), these three methods are chained together to succinctly reverse the input string. The final line, console.log(reverseString("Hello World"));, calls our function with the string “Hello World” and logs the output, which will be “dlroW olleH”, to the console.

javascript