5-4 字符串的扩展 String.prototype.padStart() String.prototype.padEnd()

47 阅读1分钟

字符串扩展: String.prototype.padStart() String.prototype.padEnd() 第一个参数是填充字符串的长度,第二个参数是可选的以什么内容去填充,如果不传会用空格去填充,返回一个新的字符串

//padStart() 从目标的前面去填充

const str = 'juejin'
console.log(str.padStart(8, 'x')) // xxjuejin

// padEnd() 从目标的后面去填充
console.log(str.padStart(8, 'y')) // juejinyy
  • yyyy-mm-dd 2023-07-01

const now = new Date()
const year = now.getFullYear()
const month = (now.getMonth() + 1).toString().padStart(2, '0')
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)

假设在我们需要13位时间戳的时候后端返回10位数字的情况下填充 0

console.log(new Date().getTime()) //13位 ms
timestamp.padEnd(13, '0')