15.5.4.15 String.prototype.substring(start, end)

2010-07-10

string String.prototype.substring(start, end)

Return a substring from this value, indicating the start and end of the substring. Unlike String.prototype.splice, negative and NaN indices will be set to 0, indices larger than len will be set to len. If start is larger than end the two are swapped.

See substr (B.2.3) to be able to specify a length instead.

The this value is coerced to a string.

String.prototype.substring.length = 2

Code: (Meta Ecma)
String.prototype.substring = 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);
var finalStart = Math.min(Math.max(intStart, 0), len);
var finalEnd = Math.min(math.max(intEnd, 0), len);
var from = Math.min(finalStart, finalEnd);
var to = Math.max(finalStart, finalEnd);
return S.substring(to, from);
}