// 截取字符串的方法
// 1. 使用 substring 方法
let str = "Hello, World!";
let result = str.substring(0, 5); // 参数为开始索引和结束索引(不包括结束索引)
console.log(result); // 输出: Hello
// 2. 使用 slice 方法
let result2 = str.slice(7, 12); // 参数为开始索引和结束索引(不包括结束索引),可以接受负数索引
console.log(result2); // 输出: World
// 3. 使用 substr 方法
let result3 = str.substr(0, 5); // 参数为开始索引和要截取的长度
console.log(result3); // 输出: Hello
// 4. 使用 match 方法结合正则表达式
let result4 = str.match(/World/)[0]; // 使用正则表达式匹配特定子串
console.log(result4); // 输出: World
// 5. 使用 split 和 join 方法组合
let result5 = str.split(", ")[1].split("!")[0]; // 先按分隔符分割,再进一步处理
console.log(result5); // 输出: World
上一篇:javascript 类
下一篇:javascript 随机数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站