DEV Community

nikhilmwarrier
nikhilmwarrier

Posted on • Originally published at nikhil.thedev.id on

1 1

Quick Tips: String Padding in JS

Quick Tip #1: String Padding in JavaScript

An example image

Use the padStart() string method with the string length and the string to fill the padding with.

Example:

const text = "Party"
text.padStart(7, "🎉 ") //"🎉 Party"

Enter fullscreen mode Exit fullscreen mode

Actual Use Case

Suppose you have an array of binary numbers which need not necessarily be in the standard 8-digit format. We want to add "padding" to it so it looks like the 8-digit eyecandy we all know and love.

Here is how to do it:

const binaryNums = [0, 1101, 011010, 1010]
const paddedBinary = []

binaryNums.forEach(num => {
  const str = num.toString(); // convert to string
  const paddedStr = str.padStart(8, "0") // fix the length of string at 8, and add padding with "0"
  paddedBinary.push(Number(paddedStr)
})

// paddedBinary = [00000000, 00001101, 00011010, 00001010]

Enter fullscreen mode Exit fullscreen mode

See the MDN Docs for more info.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay