关于字符串截取函数应该使用哪个的拙见

关于字符串截取函数应该使用哪个的拙见

JS中常用的字符串截取函数有三个。

  1. slice

    /**
    * Returns a section of a string.
    * @param start The index to the beginning of the specified portion of stringObj.
    * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.
    * If this value is not specified, the substring continues to the end of stringObj.
    */
    slice(start?: number, end?: number): string;
    
  2. substring

    /**
    * Returns the substring at the specified location within a String object.
    * @param start The zero-based index number indicating the beginning of the substring.
    * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.
    * If end is omitted, the characters from start through the end of the original string are returned.
    */
    substring(start: number, end?: number): string;
    
  3. substr

    /**
    * Gets a substring beginning at the specified location and having the specified length.
    * @deprecated A legacy feature for browser compatibility
    * @param from The starting position of the desired substring. The index of the first character in the string is zero.
    * @param length The number of characters to include in the returned substring.
    */
    substr(from: number, length?: number): string
    

可以看到slice和substring比较类似,可以接受两个参数,这两个参数都是字符串的下标。

而substr则不太一样,它的第一个参数也是下标,而第二个参数是截取的长度。

在某些情况下,截取一定的长度看起来貌似更好理解,不幸的是,我们从注解中可以看出substr已经被废弃了。MDN也这样提示我们。

image-20220706135255910

既然被废弃了,那么我们就尽量不要去使用它。

然后就是比较类似的slice和substring,我的建议是只是用slice,因为它支持负数的小标,截取起来更加方便,让熟悉python字符串截取的我们倍感亲切。

let test = "wuuconix"
test = test.slice(0, -1)
console.log(test)

image-20220706135526924

image-20220706135725978

而substring则不支持负数下标。

image-20220706135605773

所以之后遇到字符串截取问题不假思索地使用slice吧!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值