ES8 |字符串扩展

98 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

ES系列文章

ES8字符串扩展

String.prototype.padStat()

  • 把指定字符串填充到字符串开头,返回新字符串
  • 第一个参数:目标字符要保持的长度值
  • 第二个参数:如果目标字符长度不够需要补白的字符,默认为空
const str = 'imooc'
console.log(str.padStart(8, 'x'))

String.prototype.padEnd()

  • 把指定字符串填充到字符串结尾,返回新字符串
const str = 'imooc'
console.log(str.padEnd(8, 'y'))
console.log(str.padStart(8))

场景一:日期格式化成 yyyy-mm-dd

getMonth()、getDate() 返回的数据类型是 Number 类型

//yyyy-mm-dd
const now = new Date()
const year = now.getFullYear()
const month = (now.getMonth() + 1).toString().padStart(2, '0') // 0~11
const day = (now.getDate()).toString().padStart(2, '0')
console.log(`${year}-${month}-${day}`)

场景二:数字替换

const tel = '13012345678'
const newTel = tel.slice(-4).padStart(tel.length, '*')
console.log(newTel)

场景三:时间戳统一长度

  • 前端处理时间戳单位都是 ms 毫秒,后端同学返回的时间戳不一定是毫秒,可能只有10 位,以 s 秒为单位
  • 前端处理时间戳保险起见,要先做一个 13 位的补全,保证单位是毫秒
console.log(new Date().getTime()) // 13位 ms
timestamp.padEnd(13, '0') // 伪代码

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!