js 字符串截取数组常用方法总结(前端)

  1. slice(start,end)

 start: 其中start属于必填,截取开始位置;

 end:  选填,截取结束位置,且不包括结束下标位置的字符。

var str = ['Banana', 'Orange', 'Apple', 'Mango']
    console.log(str.slice(2)) // "Apple", "Mango"
    console.log(str.slice(1, 3)) // "Orange", "Apple"
    console.log(str.slice(-1)) // "Mango"
    console.log(str.slice(-3, -1)) // "Orange", "Apple"

   2. substr(start, length)

start: 必填,截取开始的位置

length: 选填,整数,需要截取的长度

 var str = '2023-04-15 11:25:00'
    console.log(str.substr(5)) // 04-15 11:25:00
    console.log(str.substr(0, 4)) // 2023
    console.log(str.substr(-9)) // 11:25:00
    console.log(str.substr(-9, 9)) //  11:25:00

3. substring(from, to)

from: 必填,非负整数,下标从0开始

to:选填,非负整数,比要提取的字符串的最后一个字符在string Object中的位置多1

注意:所有负数都视为下标0处理

var str = '2023-04-15 11:25:00'
    console.log(str.substring(5)) // 04-15 11:25:00
    console.log(str.substring(0, 4)) // 2023
    console.log(str.substring(-9)) // 2023-04-15 11:25:00
    console.log(str.substring(-9, 9)) //  2023-04-1

 4. splice(index, num,insertValue)

index:必填,整数,规定添加/删除下标的位置,负数表示从数组结尾处规定位置

num: 必需,要删除的下标数量,如设置0则不会删除项目

insertValue: 选填,向数组添加的新项目

删除从index=-2 即倒数第二个元素开始,删除3个,即5,6(只有两个);并在倒数第二个元素前添加8,9 

 var array = [0, 1, 2, 3, 4, 5, 6]
    console.log('原数组为:', array)  //[0, 1, 2, 3, 4, 5, 6]
    var arrBack = array.splice(-2, 3, 8, 9) 
    console.log('array:', array) //[0, 1, 2, 3, 4, 8, 9]
    console.log('arrBack:', arrBack) //[5, 6]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值