EN
TypeScript - pad left number in string with zeros or spaces to get determined length
3
points
In TypeScript, it is possible to pad left a number with any character in the following ways.
1. Custom solution example
const padLeft = (number: number, length: number, character: string = '0'): string => {
let result = String(number);
for (let 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.
Simple steps:
1. install ts-polyfill
package:
npm install ts-polyfill
2. inside tsconfig.json
add es2017.string
to the lib
.
{
"version" : "3.0.3",
"compilerOptions" : {
"target": "ES6",
//...
"lib": ["es2017.string", /*...*/]
//...
},
"include": [
"./**/*.ts"
]
}
3. Run the example
The example below was executed under Node.js:
// https://github.com/ryanelian/ts-polyfill
// https://developer.mozilla.org/en-US/docs/Web/TypeScript/Reference/Global_Objects/String/padStart
import 'ts-polyfill/lib/es2017-string';
const 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, '*'));
Warning: under Node.js do not forget to add
console.log()
declarations.
Output:
123
123
123
000123
***123