JS: String.prototype.slice

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

Return a string from index start to end.

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

Return a string from index start to end.

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

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

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

🛑 warning: if string contains a character outside of Basic Multilingual Plane (such as most emoji 🦋 or rarely used Chinese character), result of string methods may be unexpected. See JS: String Index and Code Unit.

Working with unicode string

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

// correct way to take a slice of string that contains emoji.
console.assert(
 Array.from("🦋bc").slice(0, 2).join("") === "🦋b",
);

// if you just use slice , you get incorrect result.
console.assert(
 "a🦋bc".slice(0, 2) === "a🦋" === false,
);