EN
JavaScript - pad right number in string with zeros or spaces to get determined length
8 points
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 insideString
class (Example 2 and 3) - introduced in ES2017 - is not supported in older browsers.
In this section custom solution on how to pad any characters on the right side is presented.
xxxxxxxxxx
1
function padRight(number, length, character) {
2
if (character == null) {
3
character = ' ';
4
}
5
var result = new String(number);
6
for (var i = result.length; i < length; ++i) {
7
result += character;
8
}
9
return result;
10
}
11
12
// Usage example:
13
14
console.log(padRight(123, 2) + ' ' + padRight(456, 2));
15
console.log(padRight(123, 4) + ' ' + padRight(456, 4));
16
console.log(padRight(123, 6, ' ') + ' ' + padRight(456, 6, ' '));
17
console.log(padRight(123, 6, '*'));
18
console.log(padRight(123, 6, '.'));
19
console.log(padRight(123, 6, '0'));
ECMAScript 2017 introduced a function that pads numbers.
In this section presented code uses copied method from the polyfill library.
xxxxxxxxxx
1
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
2
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
3
if (!String.prototype.padEnd) {
4
String.prototype.padEnd = function padEnd(targetLength,padString) {
5
targetLength = targetLength>>0; //floor if number or convert non-number to 0;
6
padString = String((typeof padString !== 'undefined' ? padString : ' '));
7
if (this.length > targetLength) {
8
return String(this);
9
}
10
else {
11
targetLength = targetLength-this.length;
12
if (targetLength > padString.length) {
13
padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
14
}
15
return String(this) + padString.slice(0,targetLength);
16
}
17
};
18
}
19
20
21
var text1 = '123';
22
var text2 = '456';
23
24
console.log(text1.padEnd(2) + ' ' + text2.padEnd(2));
25
console.log(text1.padEnd(4) + ' ' + text2.padEnd(4));
26
console.log(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
27
console.log(text1.padEnd(6, '*'));
28
console.log(text1.padEnd(6, '.'));
29
console.log(text1.padEnd(6, '0'));
In this section presented code uses a polyfill library.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-polyfills/0.1.42/polyfill.min.js"></script>
5
</head>
6
<body>
7
<pre><script>
8
9
var text1 = '123';
10
var text2 = '456';
11
12
document.writeln(text1.padEnd(2) + ' ' + text2.padEnd(2));
13
document.writeln(text1.padEnd(4) + ' ' + text2.padEnd(4));
14
document.writeln(text1.padEnd(6, ' ') + ' ' + text2.padEnd(6, ' '));
15
document.writeln(text1.padEnd(6, '*'));
16
document.writeln(text1.padEnd(6, '.'));
17
document.writeln(text1.padEnd(6, '0'));
18
19
</script></pre>
20
</body>
21
</html>