The best way to pad a string in JavaScript
Tags: javascript, beginners, codenewbie, webdev
Published: 2023-11-07 11:28:25

Padding a string means filling up a string with another character sequence or string. For example, you have written a function to the time formatted in `hh:mm:ss` format.

```javascript

function getTime() {
  const hour = new Date().getHours();
  const min = new Date().getMinutes();
  const sec = new Date().getSeconds();
  
  return `${hour}:${min}:${sec}`
}
```

When you run the above code, it will return a time format string like:

![time in format](https://cdn.hashnode.com/res/hashnode/image/upload/v1698817744846/452b5584-05c9-4216-bc90-d9a1f80d0d62.png)

However, you will also get the output where either of hour, minute, or second value may appear in the single digit:

![time needs padding](https://cdn.hashnode.com/res/hashnode/image/upload/v1698818629560/91504bb9-4d05-428c-acd3-caf1b4f48a90.png)

Now, you may want to pad the single-digit value with an additional 0 in the beginning so that the format always remains as `hh:mm:ss`.

One of the ways you can handle it is by checking if the hour, minute, or second is in single digits and then appending an `0` in front of it. It works.

```javascript
function getTime() {
  let hour = new Date().getHours();
  hour = hour <=9 ? `0${hour}` : hour;

  let min = new Date().getMinutes();
  min = min <=9 ? `0${min}` : min;

  const sec = new Date().getSeconds();
  sec = sec <=9 ? `0${sec}` : sec;
  
  return `${hour}:${min}:${sec}`
}
```

But there is a better way!

## Welcome the `padStart()` method

The `padStart()` method of JavaScript string helps you to pad a string with another string until it reaches a desired length. The padding takes place from the beginning of the string. Finally, the method returns the padded string.

```javascript
const digit = "9";
const paddedDiggit = digit.padStart(4,"0");

console.log(paddedDiggit); // Output is 0009
```

In the above code snippet, we have used the `padStart()` method to pad a string(`9`) with another string `0`, until the padded string length becomes `4`. Hence, the output is `0009`.

The `padStart()` methods can take up to two parameters:

```javascript
padStart(targetLength, padString);
```

The `padString` parameter is optional. Its default value is the Unicode "space" character.

## Let's solve the time format problem

Now, let us solve the time format issue using the `padStart()` method. So, we need to pad the single digits with an `0` in the front and make the padded string a double-digit string.

We can write a function like,

```javascript
function padByZero(input) {
  return input.toString().padStart(2, '0');
}
```

This above function accepts an input parameter and uses the `toString()` method to convert it into a string. Then, it calls the `padStart()` method with two arguments, the first one being the padded string length and the second one being the string to pad with.

Hence `padByZero(8)` will return `08`. We can now use the `padByZero()` function in the `getTime()` function to pad the single-digit values.

```javascript
function getTime() {
  let hour = padByZero(new Date().getHours());
  let min = padByZero(new Date().getMinutes());
  let sec = padByZero(new Date().getSeconds());
  
  return `${hour}:${min}:${sec}`
}
```

That's it! Now, the output format will always be `hh:mm:ss`.

## There is a `padEnd()` method too

The `padEnd()` method of JavaScript string helps you to pad a string with another string until it reaches a desired length. Finally, the method returns the padded string. In this case, the padding takes place from the end of the string.

```javascript
const digit = "9";
const paddedDiggit = digit.padEnd(4,"0");

console.log(paddedDiggit); // Output is 9000
```

That's all. Thanks for reading it. I hope it was insightful. If you liked the tutorial, please post likes and share it in your circles.

> You can also find a YouTube Shorts on this topic:
> 
> {% youtube Wy37r57b-1Q %} 

---

## **Before We End...**

Let's connect. I share web development, content creation, Open Source, and career tips on these platforms.

* [**tapaScript on YouTube**](https://www.youtube.com/tapasadhikary?sub_confirmation=1)
    
* [**X(eka Twitter)**](https://twitter.com/tapasadhikary)
    
* [**LinkedIn**](https://www.linkedin.com/in/tapasadhikary/)
    
* [**GitHub**](https://github.com/atapas)