【ES8(2017)】String扩展 padStart / padEnd
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【ES8(2017)】String扩展 padStart / padEnd
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                文章目錄
- 1. String.prototype.padStart()
- 2. String.prototype.padEnd()
1. String.prototype.padStart()
把指定字符串填充到字符串頭部,返回新字符串。
語法:str.padStart(targetLength [, padString])
const str = 'hello' console.log(str.padStart(8, 'x')) // xxxhello console.log(str.padEnd(8, 'y')) // helloyyy console.log(str.padStart(8)) // hello日期格式化:
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) // 2021,05,11 console.log( `${year}-${month}-${day}` ) // 2021-05-11數字替換:
const tel = '18612345678' const newTel = tel.slice(-4).padStart(tel.length, '*') console.log(newTel) // *******56782. String.prototype.padEnd()
用一個字符串填充當前字符串(如果需要的話則重復填充),返回填充后達到指定長度的字符串。從當前字符串的末尾(右側)開始填充。
const str1 = 'I am xiaoming' console.log(str1.padEnd(20, '.')) // I am xiaoming.......const str2 = '200' console.log(str2.padEnd(5)) // "200 "統一時間戳長度,時間戳不一定是毫秒,可能只有10位,以s秒為單位。所以,我們在前端處理這個時間戳的時候,保險起見,要先做一個13位的補全,保證單位是毫秒。
String(timestamp).padEnd(13, '0')總結
以上是生活随笔為你收集整理的【ES8(2017)】String扩展 padStart / padEnd的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Vue第一部分(2): 数据的渲染
- 下一篇: 可用资源不足excel无法完成任务_项目
