How to reverse a string in Javascript. In this tutorial, I am going to explain three simple ways to reverse a string in javascript. This question is asked by Shashank on my WebRewrite Facebook page.
How to Reverse a String in Javascript – Method 1
Javascript does not provide direct method for string reversal. Using little trick, we can reverse a string in javascript by using in-built functions.
In Javascript, we can easily reverse a string using split, reverse and join method.
1 2 3 4 5 6 7 8 9 10 |
//Declare string var str= "webrewrite.com"; var result = str.split("").reverse().join(""); console.log(result); /* Output */ moc.etirwerbew |
In the above code example, first we are splitting the string into individual character array, then we are reversing the character array and finally we join them back together with no space in between.
I am going to explain step by step, how above code snippet reverse a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/* First string is converted into an array using split method. */ console.log(str.split("")); ["w", "e", "b", "r", "e", "w", "r", "i", "t", "e", ".", "c", "o", "m"] /* Then array reverse method reversed the array. */ console.log(str.split("").reverse()); ["m", "o", "c", ".", "e", "t", "i", "r", "w", "e", "r", "b", "e", "w"] /* After the array is reversed join them using join method. */ console.log(str.split("").reverse().join("")); /* Final output reverse string. */ moc.etirwerbew |
Create function.
1 2 3 |
function reverseStr(str) { return str.split('').reverse().join(''); } |
Check value exists in array using Javascript
Add Reverse Method to String Prototype
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String.prototype.reverse = function() { return this.split('').reverse().join(''); } var str = "webrewrite.com"; /* Call Reverse Method. */ console.log(str.reverse()); /* Output */ moc.etirwerbew |
Reverse a String in Javascript using Custom Method
i) We have seen, how we can reverse a string in javascript using in-built method. In this example, we are going to create a custom function which reverse a string using swapping.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function reverse(str) { /* Convert the string into array. */ str = str.split(''); /* Take the length. */ var len = str.length, //mid index midValue = Math.floor(len / 2) - 1, tmp; /* Swap the position. */ for (var i = 0; i <=midValue ; i++) { tmp = str[len - i - 1]; str[len - i - 1] = str[i]; str[i] = tmp; } /* Convert the array into string. */ return str.join(''); } /* Calling reverse method. */ var revStr = reverse("webrewrite"); console.log(revStr); |