// 示例代码:使用 JavaScript 截取字符串
// 定义一个字符串
let str = "Hello, World!";
// 使用 substring 方法截取从索引 0 到 5 的子字符串(不包括索引 5)
let result1 = str.substring(0, 5);
console.log(result1); // 输出: Hello
// 使用 slice 方法截取从索引 7 到末尾的子字符串
let result2 = str.slice(7);
console.log(result2); // 输出: World!
// 使用 substr 方法截取从索引 0 开始的前 5 个字符
let result3 = str.substr(0, 5);
console.log(result3); // 输出: Hello
// 解释说明:
// 1. substring(startIndex, endIndex):返回从 startIndex 到 endIndex - 1 的子字符串。
// 2. slice(startIndex, endIndex):与 substring 类似,但支持负数索引(从字符串末尾开始计数)。
// 3. substr(startIndex, length):返回从 startIndex 开始的指定长度的子字符串。
上一篇:js 时间格式转时间戳
下一篇:js object 转数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站