To reverse a string in JavaScript:
- Use the
split()
method to split a string into an array of substrings using a separator. - Pass the array to the
reverse()
method to reverse the order of the elements in an array. - Use the
join()
method to join all elements of an array into a string and returns the new string.
const str = 'john doe'
const tokens = str.split('')
// [ 'j', 'o', 'h', 'n', ' ', 'd', 'o', 'e']
const reversed = tokens.reverse()
// ['e', 'o', 'd', ' ', 'n', 'h', 'o', 'j']
const finalStr = reversed.join('')
console.log(finalStr)
// eod nhoj
The reverse()
method reverses the order of the elements in an array. The first element becomes the last, and the last element becomes the first.
The join()
method joins all elements of an array into a string and returns the new string.
You can also combine these three methods together and create a function as shown below:
const reverseStr = str => {
return str.split('').reverse().join('')
}
reverseStr('hello world!')
// => !dlrow olleh
Reverse a string using a decrementing loop
Reversing a string using for loop might appear naive, but it works well. We can use decrementing (or even incrementing) loop to iterate over each character of the string and create a new reversed string:
const reverseStr = str => {
let reversed = ''
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i]
}
return reversed
}
reverseStr('hello world!')
// => !dlrow olleh
A modern for loop syntax using ES6 for...of
:
const reverseStr = str => {
let reversed = ''
for (const c of str) {
reversed = c + reversed
}
return reversed
}
Reverse a string using recursion
Recursion is another way to reverse a string in JavaScript. This approach involves two JavaScript functions: substr()
and charAt()
.
The first method returns a substring of a string and the second method returns the specified character of a string.
const reverseStr = str => {
return str ? reverseStr(str.substr(1)) + str[0] : str
}
reverseStr('hello world!')
// => !dlrow olleh
The number of times the recursive function is called, depends on the length of the string. It will become slow if the string is very long. So this is not a very good solution but still a way to solve the challenge.
Reverse a string using the reduce()
method
Another rarely used approach to reverse a string in JavaScript is using the Array.reduce()
function.
This method reduces the array to a single value. Since this function works for arrays, we first need to split the string into an array using the split()
method.
const reverseStr = str => {
return str.split('').reduce((r, c) => c + r, '')
}
reverseStr('hello world!')
// => !dlrow olleh
Summary
There are tons of different ways to reverse a string in JavaScript. In this tutorial, we have discussed 4 different approaches to solving the reverse string challenge:
- Using built-in JavaScript functions like
split()
,reverse()
, andslice()
. It is straightforward and perhaps the best approach. - Using for loop to iterate over all characters of a string and create a new reversed string.
- Recursively convert the string into a substring until the empty string is reached, and then combine them to form a reversed string. It may become slow if the string is large.
- Splitting the string into an array and then reducing the array into a single value using the
Array.reduce()
function.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.