숫자를 웹상에 문자로 표현을 할 때, 자리수만큼 앞에 0을 채워야 하는 경우가 있다.
//숫자 프로토타입으로 입력 길이만큼 앞에 0을 채운 문자열 반환
Number.prototype.fillZero = function(width){
let n = String(this);//문자열 변환
return n.length >= width ? n:new Array(width-n.length+1).join('0')+n;
//남는 길이만큼 0으로 채움
}
//문자열 프로토타입으로 입력 길이만큼 앞에 0을 채운 문자열 반환
String.prototype.fillZero = function(width){
return this.length >= width ? this:new Array(width-this.length+1).join('0')+this;
//남는 길이만큼 0으로 채움
}
//문자열 프로토타입으로 입력 길이만큼 앞에 pad 문자로 채운 문자열 반환
String.prototype.fillPadStart = function(width, pad){
return this.length >= width ? this : new Array(width-this.length+1).join(pad)+this;
//남는 길이만큼 pad로 앞을 채움
}
//문자열 프로토타입으로 입력 길이만큼 앞에 pad 문자로 채운 문자열 반환
String.prototype.fillPadEnd = function(width, pad){
return this.length >= width ? this : this + new Array(width-this.length+1).join(pad);
//남는 길이만큼 pad로 뒤를 채움
}
'03'.padStart(6,'0'); // '000003'
'2500'.padStart(8,'$'); // "$$$$2500"
'12345'.padStart(10); // " 12345"
'abc'.padEnd(9,'123'); // "abc123123"
'주석문'.padStart(6,'*').padEnd(9,'*'); // "***주석문***"
var dt = new Date();
console.log(dt.getFullYear()+ '-' + dt.getMonth().toString().padStart(2,'0') + '-' + dt.getDate().toString().padStart(2,'0')); // "2020-05-09"