JS: String.prototype.substring ❌

By Xah Lee. Date: . Last updated: .

🟢 TIP: better is String.prototype.slice

str.substring(start, end)

return a substring from start to end.

  • If any argument is negative, it is replaced by 0.
  • If any argument is greater than length, it's replaced by length.
  • If start greater than end, swap them
// end does not include itself
console.log("0123".substring(1, 3));
// 12

// end by default is end of string
console.log("0123".substring(1));
// 123

Edge cases

// if start greater than end, swap them
console.log("0123456".substring(3, 1));
// 12

// s------------------------------

// if start is negative, replace it by 0
console.log("0123456".substring(-1));
// 0123456

// if end is negative, replace it by 0.
// this is same as substring(0,1)
console.log("0123456".substring(1, -1));
// 0

// this is same as substring(0,3)
console.log("0123456".substring(3, -1));
// 012

// this is same as substring(0,0)
console.log("0123456".substring(-3, -1));
// ""

// s------------------------------

// no args. return the full string.
console.log("0123456".substring());
// 0123456

JavaScript. substring

JS String.prototype