How to pad a string with X in JavaScript - padStart() method example

← PrevNext →

The JavaScript padStart() method pads the current string with another string, multiple times, until it reaches the given length. Let us see some examples to understand how it works and where you can use the padStart() method.

image

JavaScript string padStart() method example

Syntax

.padStart(length)

.padStart(length, new_string)

Arguments…

length: the length of the string that will be padded to the current string.

new_string: or a new string, which is to be padded to the current string.

Where it is used?

Did you ever receive a message from your Bank that read, "Your xyz bank A/c XX1234 is inactive since so-and-so date" and some other message that refers to your bank account number that starts with a prefix XX? I am sure you have, if you have an account.

There are other real case scenarios too.

So, the string .padStart() method can be used to add or pad a prefix to a string, like the bank account number etc.

Note: to pad suffix or a string after the current string, you can use .padEnd() method.

Here’s an example using the bank account concept.

<script>
  const act_no = '1234';
  console.log (act_no.padStart(6, 'X'));      // Output: XX1234
</script>
Try it

Now, lets understand what the code is doing.

The string act_no has a 4-digit value. I want to pad (or fill) two XX values at the beginning of the string.

Therefore, the length I have defined is 6 (since the current string already has 4 values) and the string XX to pad.

Pad multiple times

You can pad a string multiple times to the current string. For example,

<script>
  const str = 'bong';
  console.log (str.padStart(10, 'boo'));      // Output: booboobong
</script>
Try it

Dynamic string argument

The .padStart() method can take two arguments, the length and a new string. The new string can be passed in form of a variable. For example,

<script>
  const str = '1234';
  const prefix = 'MP-16-CL-';
  console.log (str.padStart(13, prefix));   // padStart has a dynamic argument.
  // Output: MP-16-CL-1234
</script>
Try it

Pad blank space to string

You can add or pad blank spaces before a string, by not assigning any a new as argument.

<script>
  const str = '1234';
  console.log (str.padStart(10));   // Output: "      1234"
</script>

Happy coding.

← PreviousNext →