substring Clamps Indices While slice Takes Negatives
substring clamps out-of-range and negative indices and swaps reversed arguments, while slice counts negatives from the end and returns an empty string instead.
Code
const name = 'deploy';
// 负数与越界:substring 全部钳到 [0, length],slice 允许负数从末尾倒数
console.log("substring(-2) :", name.substring(-2), "| slice(-2) :", name.slice(-2));
console.log("substring(2, 99):", name.substring(2, 99), "| slice(2, 99) :", name.slice(2, 99));
// substring 里 start > end 会自动交换;slice 直接返回空串
console.log("substring(4, 2) :", name.substring(4, 2), "| slice(4, 2) :", JSON.stringify(name.slice(4, 2)));
// 相同的正向区间:两者一致
console.log("substring(1, 3) :", name.substring(1, 3), "| slice(1, 3) :", name.slice(1, 3));
// NaN 参数被当作 0:来自数字解析的坐标不会抛错
console.log("substring(NaN) :", JSON.stringify(name.substring(NaN, 3)), "| slice(NaN, 3) :", JSON.stringify(name.slice(NaN, 3)));
// slice 支持负数区间:取文件名主干或扩展名的惯用法
const file = 'report-2026.pdf';
console.log("stem :", file.slice(0, file.lastIndexOf('.')));
console.log("ext :", file.slice(file.lastIndexOf('.') + 1));Output
Captured from a sandboxed run of this snippet in the build pipeline.
substring(-2) : deploy | slice(-2) : oy
substring(2, 99): ploy | slice(2, 99) : ploy
substring(4, 2) : pl | slice(4, 2) : ""
substring(1, 3) : ep | slice(1, 3) : ep
substring(NaN) : "dep" | slice(NaN, 3) : "dep"
stem : report-2026
ext : pdfHow it works
The demo data lives in module-level bindings: name, file.
Watch out for
- Ready as-is on a bare install of the language.
Using it
Output lines are prefixed (substring(-2) :, substring(2, 99):, substring(4, 2) :), making each step’s effect easy to spot.
Key statements
const file = 'report-2026.pdf';
const name = 'deploy';
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `name`, `file`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.