Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call [].reverse on a string

Tags:

javascript

Why does

[].reverse.call("string");

fails (error in both firefox and ie, returns the original string in chrome) while calling all other arrays methods on a string work ?

>>> [].splice.call("string",3)
["i", "n", "g"]
>>> [].map.call("string",function (a) {return a +a;} )
["ss", "tt", "rr", "ii", "nn", "gg"]
like image 743
Hai Avatar asked Jan 15 '12 00:01

Hai


People also ask

How do you reverse call a string?

var s = "string"; var s2 = []. slice. call(s). reverse().

Can you use reverse () on a string?

String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder.

How do you reverse the reverse order of a string?

The reversing of a string is nothing but simply substituting the last element of a string to the 1st position of the string. Different Methods to Reverse a String in C++ are: Making our own reverse function. Using 'inbuilt' reverse function.


1 Answers

Because .reverse() modifies an Array, and strings are immutable.


You could borrow Array.prototype.slice to convert to an Array, then reverse and join it.

var s = "string";

var s2 = [].slice.call(s).reverse().join('');

Just be aware that in older versions of IE, you can't manipulate a string like an Array.

like image 130
user1106925 Avatar answered Sep 19 '22 05:09

user1106925