Languages
[Edit]
EN

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

8 points
Created by:
elmer
646

In JavaScript it is possible to pad any number with some character in the following ways:

  • with simple custom method (Example 1),
  • with padEnd method placed inside String class (Example 2 and 3) - introduced in ES2017 - is not supported in older browsers.

1. Custom solution example

In this section custom solution on how to pad any characters on the right side is presented.

// ONLINE-RUNNER:browser;

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

// Usage example:

console.log(padRight(123, 2) + ' ' + padRight(456, 2));
console.log(padRight(123, 4) + ' ' + padRight(456, 4));
console.log(padRight(123, 6, ' ') + ' ' + padRight(456, 6, ' '));
console.log(padRight(123, 6, '*'));
console.log(padRight(123, 6, '.'));
console.log(padRight(123, 6, '0'));

2. Polifill example

ECMAScript 2017 introduced a function that pads numbers.

2.1. Inline code example

In this section presented code uses copied method from the polyfill library.

// 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/padEnd
if (!String.prototype.padEnd) {
    String.prototype.padEnd = function padEnd(targetLength,padString) {
        targetLength = targetLength>>0; //floor 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 String(this) + padString.slice(0,targetLength);
        }
    };
}


var text1 = '123';
var text2 = '456';

console.log(text1.padEnd(2) + ' ' + text2.padEnd(2));
console.log(text1.padEnd(4) + ' ' + text2.padEnd(4));
console.log(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
console.log(text1.padEnd(6, '*'));
console.log(text1.padEnd(6, '.'));
console.log(text1.padEnd(6, '0'));

2.2. Included code example

In this section presented code uses a polyfill library.

// 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 text1 = '123';
      var text2 = '456';

      document.writeln(text1.padEnd(2) + ' ' + text2.padEnd(2));
      document.writeln(text1.padEnd(4) + ' ' + text2.padEnd(4));
      document.writeln(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
      document.writeln(text1.padEnd(6, '*'));
      document.writeln(text1.padEnd(6, '.'));
      document.writeln(text1.padEnd(6, '0'));

  </script></pre>
</body>
</html>
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