JS: String.prototype.slice

By Xah Lee. Date: . Last updated: .
str.slice(start)
Return a substring from index start to end.
str.slice(start, end)
Return a substring from index start to end.
const ss = "abcd";

console.log( ss.slice(1,3) ); // bc

// think of index as between characters
// index before first char is 0
// index after last char is length
// negative index counts from the end, right to left

console.log( ss.slice(0, ss.length) ); // abcd
console.log( ss.slice() ); // abcd
console.log( ss.slice(1) ); // bcd
console.log( ss.slice(-1) ); // d
console.log( ss.slice(-2) ); // cd

// same index, empty string
console.log( ss.slice(2, 2) === "" ); // true

// when start index is greater than end index, result is empty string
console.log( ss.slice(3, 2) === "" ); // true
console.log( ss.slice(-2, -3) === "" ); // true

Note: "😂".length === 2 [see JS: String Code Unit]

JavaScript, substring

BUY ΣJS JavaScript in Depth