ES6字符串常用新增方法

1.includes()

在ES5中,我们常用indexOf()来判断某个字符串中是否包含另一个字符串,如下:

var str = 'hello world!'
    var result = str.indexOf('lo') < 0 ? false : true
    console.log(result) // true

这样我们需要加一层判断来得到我们需要的是否该字符串中存在某个字符串与否,ES6提供了更加简便的方法来达到这个效果

var str = 'hello world!'
    var result = str.includes('uo')
    console.log(result) // false

2.startsWith(),表示参数字符串是否在原字符串的头部

var str = 'hello world!'
    var result = str.startsWith('hel')
    console.log(result) // true

3.endsWith(),表示参数字符串是否在原字符串的尾部

var str = 'hello world!'
    var result = str.endsWith('hel')
    console.log(result) // false

4.字符串的遍历器接口,使得字符串可以被for...of循环遍历

var str = 'hell'
    for(let item of str){
      console.log(item) // 'h' 'e' 'l' 'l'
    }

5.repeat(),返回一个新字符串,表示将原字符串重复n次

'xx'.repeat(2) // 'xxxx'
    'hello'.repeat(3) // 'hellohellohello'
    'li'.repeat(0) // ''
    'li'.repeat(Infinity) // RangeError
    'li'.repeat(-2) // RangeError

需要注意的是,repeat()的参数不能为负数或者Infinity,否则报错

6.padStart(),padEnd(),如果某个字符串不够制定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全

console.log('aa'.padStart(5,'s')) // sssaa
    console.log('aa'.padEnd(6,'g')) // aagggg

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值