3 Ways to Reverse a String in JavaScript
Learn how to reverse a string in JavaScript
One of the more common things you may be asked to do in a technical interview is a string reversal. I'm going to show you three different ways to execute a string reversal so you can nail that part of the process, the first one is a function and the last two are methods.
So let's go!
A reversal is straight forward, the first element becomes the last and the last element becomes the first.
Below is a function that does a string reversal, it is the longest of the code snippets I've provided.
function reverse(str) {
if(!str || str.length < 2 || typeof str != 'string') return str;
const backwards = []
const totalItems = str.length - 1
for (let i = totalItems; i >= 0; i--) {
backwards.push(str[i])
}
return backwards.join('')
}
console.log(reverse('Hi my name is Shamel'))
// Output lemahS si eman ym iH
Let's break down the code:
- Check the input of the string.
- Check to see
if
the string is less than two characters. - We are also checking
if
it's a string type. - Create an empty array
const backwards = []
- Loop from the end to beginning of the string.
.push()
elements into backwards array.- Return the array and
.join()
into a string.
Here is another example using the methods .split()
, .reverse()
and .join()
function reverse2(str){
return str.split('').reverse().join('')
}
console.log(reverse2("Now I'm learning"));
// Outputs gninrael m'I woN
Let's make it shorter!
Here's an example of string reversal in one line using only two methods .reverse()
and .join()
.
const reverse3 = str => [...str].reverse().join('')
console.log(reverse3("Look Ma no hands!"))
// Output !sdnah on aM kooL
Now you know how to reverse a string three different ways!
🏆 Fin.