Marcos
Marcos

Reputation: 4643

JavaScript String Object to String

In node.js the next code

var Reverse = (function() {

    return {
        reverse1: function(s) {
            var out = new String();
            for (var i = s.length - 1, j = 0; i >= 0; i--, j++) {
                out[j] = s[i];
            }
            return out;
        }
    }
})();

console.log(Reverse.reverse1("this is text"));

prints

{ '0': 't',
  '1': 'x',
  '2': 'e',
  '3': 't',
  '4': ' ',
  '5': 's',
  '6': 'i',
  '7': ' ',
  '8': 's',
  '9': 'i',
  '10': 'h',
  '11': 't' 
}

But I want to print a string. I've tried return out.toString() but returns nothing.

Upvotes: 1

Views: 209

Answers (4)

MagePal Extensions
MagePal Extensions

Reputation: 17656

var Reverse = (function() {

    return {
        reverse1: function(s) {
            out = '';
            for (var i = s.length - 1; i >= 0; i--) {
                out += s[i];
            }
            return out;
        }
    }
})();

console.log(Reverse.reverse1("this is text"));

Upvotes: 1

xdazz
xdazz

Reputation: 160903

Use join method of array.

 return out.join('');

And change var out = new String(); to var out = [];

And Note:

You could do the below to reverse a string:

var ret = "this is text".split('').reverse().join('');

Upvotes: 1

Kaustubh Karkare
Kaustubh Karkare

Reputation: 1101

var Reverse = (function() {
    return {
        reverse1: function(s) {
            var out = "";
            for (var i = s.length - 1, j = 0; i >= 0; i--, j++) out += s[i];
            return out;
        }
    };
})();
console.log(Reverse.reverse1("this is text"));

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270707

Unless you have a real serious reason to need this done by array index, why not just concatenate onto it?

out += s[i];

Will print:

// "txet si siht"

Upvotes: 3

Related Questions