• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
骑着小毛驴过冬的八阿哥
博客园    首页    新随笔    联系   管理    订阅  订阅

ES6之字符串扩展

ES6字符串新增的常用方法:

1. includes(): 字符串中是否包含某个字符或字符串, 包含的两个字符必须是相连的

1 let str = 'hello, world'
2 str.includes('hel')   // true
3 str.includes('ho')    // false

 

2. startsWith() : 字符串中是否以某个字符或字符串开头 , endsWith()是否 以某个字符或字符串结束

1 let str = 'hello, world'
2 str.startsWith('hel')   // true
3 str.endsWith('ld')      // true

 

3. repeat(n) : 字符串重复n次

1 let str = 'hello'
2 str.repeat(2)  // hellohello

 

4. 字符串模板 `` :最常用, 不是单引号,而是 键盘上1左边的反单引号

1 let name = 'Mike'
2 let age = 25
3 
4 console.log(`name: ${name}, age: ${age}`)   // name: Mike, age: 25

 

5. padStart(n, str) , padEnd(n, str) :补白,在字符串 前或后补够n个长度 , 常用来作时间日期前面补0操作

1 let str = '1'
2 
3 console.log(str.padStart(2, '0'))    // '01'
4 console.log(str.padEnd(2, '0'))       // '10'

 

6.  for ...of:将字符串遍历,并且支持遍历unicode码的字符串

1 var str = 'hello'
2 for (let code of str) {
3     console.log(code)    // h, e, l, l, o
4 }

 

// 不常用的方法还有:

String.at()

String.raw()

String.normalize()

String.codePiontAt() : 扩展了charCodeAt(), 字符转码点

String.fromCodePiont()   :   扩展了fromCharCode() , 从码点返回字符

 

posted @ 2018-07-27 00:35  浅草马甲  阅读(639)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3