Categories
JavaScript Answers

How to convert ‘1’ to ‘0001’ in JavaScript?

Spread the love

Sometimes, we want to convert ‘1’ to ‘0001’ in JavaScript.

In this article, we’ll look at how to convert ‘1’ to ‘0001’ in JavaScript.

How to convert ‘1’ to ‘0001’ in JavaScript?

To convert ‘1’ to ‘0001’ in JavaScript, we can use the string padStart method.

For instance, we write

const str = "1";
const ans = str.padStart(4, '0');

to call str.padStart with 4 and '0' to prepend '0'‘s to the str string into it reaches length 4.

Therefore, ans is '0001'.

Conclusion

To convert ‘1’ to ‘0001’ in JavaScript, we can use the string padStart method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *