js实现截取
字符串截取方法
在JavaScript中,字符串截取可通过以下方法实现:
1. substring(startIndex, endIndex)
返回从startIndex到endIndex(不包括)的子字符串。若省略endIndex,则截取到字符串末尾。
const str = "Hello, World!";
console.log(str.substring(0, 5)); // 输出 "Hello"
2. slice(startIndex, endIndex)
与substring类似,但支持负数索引(从末尾开始计算)。

console.log(str.slice(-6, -1)); // 输出 "World"
3. substr(startIndex, length)
从startIndex开始截取指定长度的子字符串(不推荐使用,已废弃)。
console.log(str.substr(7, 5)); // 输出 "World"
数组截取方法
数组截取常用slice(startIndex, endIndex),返回新数组:

const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 3)); // 输出 [2, 3]
其他场景
1. 截取URL参数
使用正则表达式或URLSearchParams:
const url = "https://example.com?name=John&age=30";
const params = new URLSearchParams(url.split('?')[1]);
console.log(params.get('name')); // 输出 "John"
2. 截取文件扩展名
通过字符串分割:
const filename = "image.png";
const ext = filename.split('.').pop();
console.log(ext); // 输出 "png"






