DEV Community

Daniel Zotti
Daniel Zotti

Posted on

#LearnedToday: padStart()

The padStart() method is a built-in function in JavaScript that allows you to pad a string with specific characters at the beginning of the string.

I wish it had existed 15 years ago when I was working on a digital clock for a website. I would have written something like this:

const hours = 3; const minutes = 43; const seconds = 9; const time = [hours, minutes, seconds] .map(el => String(el).padStart(2,'0')) .join(":"); // time -> '03:43:09' 
Enter fullscreen mode Exit fullscreen mode

...and of course there is a sister method called padEnd()

🗄 Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

ℹ Browser support: https://caniuse.com/?search=padStart

Top comments (0)