15.5.4.13 String.prototype.slice(start,end)

2010-07-10

string String.prototype.slice(start:uint|mixed=0,end:uint|mixed=this.length)

Return a substring from this value. The main difference with String.prototype.substring (15.5.4.15) is that a negative start or end is treated as len+start or len+end. In that sense you could view it as an improved substring method.

The this value is coerced to string. The start and end are coerced to integers. If start and/or end is negative, it will assume to mean len+start or len+end.

String.prototype.slice.length = 2

Code: (Meta Ecma)
String.prototype.slice = function(start, end){
CheckObjectCoercible(this);
var S = ToString(this);
var len = S.length;
var intStart = ToInteger(start);
if (end === undefined) var intEnd = len;
else var intEnd = ToInteger(end);
if (intStart < 0) var from = Math.max(len+intStart, 0);
else var from = Math.min(intStart, len);
if (intEnd < 0) var from = Math.max(len+intEnd, 0);
else var from = Math.min(intEnd, len);
var span = Math.max(to-from, 0);
return S.substring(from, span); // cheating. i know.
}