EN
JavaScript - pad left number in string with zeros or spaces to get determined length
9
points
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>