Languages
[Edit]
EN

JavaScript - pad left number in string with zeros or spaces to get determined length

9 points
Created by:
Imaan-Morin
1009

In this article, we would like to show you how to pad left a number with any character in JavaScript.

1. Custom solution example

// ONLINE-RUNNER:browser;

function padLeft(number, length, character) {
	if(character == null) {
		character = '0';
    }
	var result = String(number);
	for(var i = result.length; i < length; ++i) {
		result = character + result;
	}
	return result;
}


// Usage example:

console.log(padLeft(123, 2));       // 123
console.log(padLeft(123, 4));       // 0123
console.log(padLeft(123, 6));       // 000123
console.log(padLeft(123, 6, '*'));  // ***123
console.log(padLeft(123, 6, ' '));  //    123

2. Polifill example

ECMAScript 2017 introduced a function that pads numbers.

2.1. Inline code example

// ONLINE-RUNNER:browser;

// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength, padString) {
        targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
        padString = String(typeof padString !== 'undefined' ? padString : ' ');
        if (this.length >= targetLength) {
            return String(this);
        } else {
            targetLength = targetLength - this.length;
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
            }
            return padString.slice(0, targetLength) + String(this);
        }
    };
}


var text = '123';

console.log(text.padStart(2));
console.log(text.padStart(4));
console.log(text.padStart(6));
console.log(text.padStart(6, '0'));
console.log(text.padStart(6, '*'));

2.2. Included code example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-polyfills/0.1.42/polyfill.min.js"></script>
</head>
<body>
  <pre><script>

      var text = '123';

      document.writeln(text.padStart(2));
      document.writeln(text.padStart(4));
      document.writeln(text.padStart(6));
      document.writeln(text.padStart(6, '0'));
      document.writeln(text.padStart(6, '*'));

  </script></pre>
</body>
</html>

Alternative titles

  1. JavaScript - fill number with zeros or spaces on the left side
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join