views:

2943

answers:

8

How do you reverse a string in place (or in-place) in JavaScript when passed to a function with a return statement? All without using the built-in functions? .reverse(), .charAt(), etc.

Thanks!

+1  A: 

Something like (didn't test):

var str = reverseStr( "the cow jumped over the moon" );

function reverseStr ( str ) {
  var rvStr, tR = [ ];
  str = str.split("");
  for ( var i = str.length - 1; i >= 0; i-- ) {
   tR.push( str[ i ] );
  }
  return tR.join( "" ); //noom eht revo depmuj woc eht
}
apphacker
That looks about right +1
ichiban
I made an edit to convert str to an array first because str[i] on a string is non standard and doesn't work in some js engines.
Zach
There are a lot of built-in functions used here, split, join, push; is this in scope?
RedFilter
I assumed methods of strings were out of the question.
apphacker
A fair guess, who knows...
RedFilter
I thought he said in place?
Ray Hidayat
Want to make it more complicated?? .. string.split('').reverse().join('')
J-P
+6  A: 
document.write("Hold me up to a mirror!");
window.print();
RedFilter
Reverses the letters too!
apphacker
That part of the requirements is unclear ;)
RedFilter
+7  A: 
String.prototype.reverse=function(){return this.split("").reverse().join("");}

or

String.prototype.reverse = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}
Bob
I definitely agree with the String prototype.
Jeff Meatball Yang
string concatenation is expensive. Better to build an array and join it or use concat().
apphacker
+1: Oh, uh... Is Bob short for Kate?
John Gietzen
#1 is best, #2 could be horribly slow
Infinity
A: 
function reverseString(string) {
    var reversedString = "";
    var stringLength = string.length - 1;
    for (var i = stringLength; i >= 0; i--) {
        reversedString += string[i];
    }
    return reversedString;
}
+2  A: 
function reverse(s){
    return s.split("").reverse().join("");
}
belacqua
A: 

You could try something like this. I'm sure there's some room for refactoring. I couldn't get around using the split function. Maybe someone knows of a way to do it without split.

Code to set up, can put this in your .js library

String.prototype.aggregate = function (vals, aggregateFunction) {

    var temp = '';
    for(var i = vals.length - 1; i >= 0; i-- )
    {
        temp = aggregateFunction(vals[i], temp);
    }
    return temp;
}

String.prototype.reverseLetters = function() {
    return this.aggregate(this.split(''), 
        function(current, word) { return word + current; })
}

String.prototype.reverseWords = function() {
    return this.aggregate(this.split(' '), 
        function(current, word) { return word + ' ' + current; })
}

Code to use it (has client side code, only because it was tested in a browser):

var sentence = "My Stack is Overflowing."
document.write(sentence.reverseLetters() + '<br />');
document.write(sentence.reverseWords() + '<br />');
Justin Largey
A: 

Another variation (does it work with IE?):

String.prototype.reverse = function() {
    for (i=1,s=""; i<=this.length; s+=this.substr(-i++,1)) {}
    return s;
}

EDIT:

This is without the use of built-in functions:

String.prototype.reverse = function() {
    for (i=this[-1],s=""; i>=0; s+=this[i--]) {}
    return s;
}

Note: this[-1] holds a length of the string.

However it's not possible to reverse the string in place, since the assignment to individual array elements doesn't work with String object (protected?). I.e. you can do assigns, but the resulting string doesn't change.

Thevs
A: 

The whole "reverse a string in place" is an antiquated interview question C programmers, and people who were interviewed by them (for revenge, maybe?), will ask. Unfortunately, it's the "In Place" part that no longer works because strings in pretty much any managed language (JS, C#, etc) uses immutable strings, thus defeating the whole idea of moving a string without allocating any new memory.

While the solutions above do indeed reverse a string, they do not do it without allocating more memory, and thus do not satisfy the conditions. You need to have direct access to the string as allocated, and be able to manipulate it's original memory location to be able to reverse it in place.

Personally, i really hate these kinds of interview questions, but sadly, i'm sure we'll keep seeing them for years to come.

Mozleron