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"]
var s = "string"; var s2 = []. slice. call(s). reverse().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With