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:
-
.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']
.
- Example:
-
.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']
.
- Example:
-
.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'
.
- Example:
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.