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.
xxxxxxxxxx
1
const padLeft = (number: number, length: number, character: string = '0'): string => {
2
let result = String(number);
3
for (let i = result.length; i < length; ++i) {
4
result = character + result;
5
}
6
return result;
7
};
8
9
10
// Usage example:
11
12
console.log(padLeft(123, 2)); // 123
13
console.log(padLeft(123, 4)); // 0123
14
console.log(padLeft(123, 6)); // 000123
15
console.log(padLeft(123, 6, '*')); // ***123
16
console.log(padLeft(123, 6, ' ')); // 123
ECMAScript 2017 introduced a function that pads numbers.
Simple steps:
1. install ts-polyfill
package:
xxxxxxxxxx
1
npm install ts-polyfill
2. inside tsconfig.json
add es2017.string
to the lib
.
xxxxxxxxxx
1
{
2
"version" : "3.0.3",
3
"compilerOptions" : {
4
"target": "ES6",
5
//...
6
"lib": ["es2017.string", /*...*/]
7
//...
8
},
9
"include": [
10
"./**/*.ts"
11
]
12
}
3. Run the example
The example below was executed under Node.js:
xxxxxxxxxx
1
// https://github.com/ryanelian/ts-polyfill
2
// https://developer.mozilla.org/en-US/docs/Web/TypeScript/Reference/Global_Objects/String/padStart
3
4
import 'ts-polyfill/lib/es2017-string';
5
6
const text = '123';
7
8
console.log(text.padStart(2));
9
console.log(text.padStart(4));
10
console.log(text.padStart(6));
11
console.log(text.padStart(6, '0'));
12
console.log(text.padStart(6, '*'));
Warning: under Node.js do not forget to add
console.log()
declarations.
Output:
xxxxxxxxxx
1
123
2
123
3
123
4
000123
5
***123