How do you reverse a string in place (or in-place) in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()<
This is the easiest way I think
var reverse = function(str) {
var arr = [];
for (var i = 0, len = str.length; i <= len; i++) {
arr.push(str.charAt(len - i))
}
return arr.join('');
}
console.log(reverse('I want a
In ES6, you have one more option
function reverseString (str) {
return [...str].reverse().join('')
}
reverseString('Hello');
I think String.prototype.reverse is a good way to solve this problem; the code as below;
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
var str = 'this is a good example for string reverse';
str.reverse();
-> "esrever gnirts rof elpmaxe doog a si siht";
The real answer is: you can't reverse it in place, but you can create a new string that is the reverse.
Just as an exercise to play with recursion: sometimes when you go to an interview, the interviewer may ask you how to do this using recursion, and I think the "preferred answer" might be "I would rather not do this in recursion as it can easily cause a stack overflow" (because it is O(n)
rather than O(log n)
. If it is O(log n)
, it is quite difficult to get a stack overflow -- 4 billion items could be handled by a stack level of 32, as 2 ** 32 is 4294967296. But if it is O(n)
, then it can easily get a stack overflow.
Sometimes the interviewer will still ask you, "just as an exercise, why don't you still write it using recursion?" And here it is:
String.prototype.reverse = function() {
if (this.length <= 1) return this;
else return this.slice(1).reverse() + this.slice(0,1);
}
test run:
var s = "";
for(var i = 0; i < 1000; i++) {
s += ("apple" + i);
}
console.log(s.reverse());
output:
999elppa899elppa...2elppa1elppa0elppa
To try getting a stack overflow, I changed 1000
to 10000
in Google Chrome, and it reported:
RangeError: Maximum call stack size exceeded
Keep it DRY and simple silly!!
function reverse(s){
let str = s;
var reverse = '';
for (var i=str.length;i>0;i--){
var newstr = str.substring(0,i)
reverse += newstr.substr(-1,1)
}
return reverse;
}
Best ways to reverse a string in JavaScript
1) Array.reverse:
You’re probably thinking, wait I thought we were reversing a string, why are you using the Array.reverse method. Using the String.split method we are converting our string into an Array of characters. Then we are reversing the order of each value in the array and then finally we convert the Array back to a String using the Array.join method.
function reverseString(str) {
return str.split('').reverse().join('');
}
reverseString('dwayne');
2) Decrementing while-loop:
Although pretty verbose, this solution does have its advantages over solution one. You’re not creating an array and you’re just concatenating a string based on characters from the source string.
From a performance perspective, this one would probably yield the best results (although untested). For extremely long strings, the performance gains might drop out the window though.
function reverseString(str) {
var temp = '';
var i = str.length;
while (i > 0) {
temp += str.substring(i - 1, i);
i--;
}
return temp;
}
reverseString('dwayne');
3) Recursion
I love how simple and clear this solution is. You can clearly see that the String.charAt and String.substr methods are being used to pass through a different value by calling itself each time until the string is empty of which the ternary would just return an empty string instead of using recursion to call itself. This would probably yield the second best performance after the second solution.
function reverseString(str) {
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('dwayne');