← 中文资源

简体中文版本

substring 钳制下标而 slice 接受负数

substring 把负数与越界一律钳进 [0, length] 并自动交换颠倒的参数,slice 用负数从末尾倒数、区间颠倒时返回空串;两者对正向区间结果一致。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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             : pdf

实现说明

各个操作都建立在顶层绑定之上:name、file。

使用要点

  • 演示输出是带标签的(substring(2, 99):、substring(4, 2) :、substring(1, 3) :),每个操作都会留下自己的一行标注。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 跨调用保留的状态放在这些顶层绑定里:name、file。

核心语句

const file = 'report-2026.pdf';
const name = 'deploy';

代码示例

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));