// 示例代码:截取字符串
// 使用 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
// 解释说明:
// 1. substring(startIndex, endIndex):返回一个新字符串,包含从 startIndex 到 endIndex(不包括 endIndex)之间的字符。
// 2. slice(startIndex, endIndex):与 substring 类似,但可以接受负数索引,表示从字符串末尾开始计算。
// 3. substr(startIndex, length):返回从 startIndex 开始的指定长度的子字符串。注意:substr 已被标记为遗留方法,不推荐在新代码中使用。
上一篇:js 字符串split
下一篇:js 判断对象是否存在某个属性
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站