实现说明
各个操作都建立在顶层绑定之上: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));