// 示例代码:截取字符串
// 使用 substring 方法
let str = "Hello, World!";
let result = str.substring(0, 5); // 截取从索引 0 到索引 5(不包括索引 5)的子字符串
console.log(result); // 输出: Hello
// 使用 slice 方法
let result2 = str.slice(7, 12); // 截取从索引 7 到索引 12(不包括索引 12)的子字符串
console.log(result2); // 输出: World
// 使用 substr 方法
let result3 = str.substr(0, 5); // 截取从索引 0 开始,长度为 5 的子字符串
console.log(result3); // 输出: Hello
substring(startIndex, endIndex)
:
startIndex
是开始截取的位置。endIndex
是结束截取的位置(不包括该位置的字符)。endIndex
省略,则截取到字符串末尾。slice(startIndex, endIndex)
:
substring
,但可以接受负数索引,表示从字符串末尾开始计算。substr(startIndex, length)
:
startIndex
是开始截取的位置。length
是要截取的字符数。substr
已经被标记为过时,建议使用 substring
或 slice
。上一篇:javascript ?.
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站