JS: String.prototype.slice

By Xah Lee. Date: . Last updated: .
str.slice(start)

Return a substring from index start to end.

console.log("abcd".slice(1, 3) === "bc");
str.slice(start, end)

Return a substring from index start to end.

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

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

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

🛑 WARNING: string methods do not work the way you think if it contains characters outside of Unicode Basic Multilingual Plane (e.g. emoji 🦋.). See JS: String Code Unit

Dealing with unicode string

If the string contains unicode emoji, turn it to array by Array.from then use splice or toSpliced.

// take a substring of string that contains emoji
console.log(Array.from("🦋bc").slice(0, 2).join(""));
// 🦋b

// bad
console.log("a🦋bc".slice(0, 2));
// a�

JavaScript. substring

JS String.prototype