Notice
Recent Posts
Recent Comments
Link
kimmgamjja
[JavaScript] 자리수 남은 만큼 0으로 채우기 pad 본문
728x90
1. 함수로 구현
자리수만큼 남은 앞부분을 0으로 채움
function fillZero(width, str){
return str.length >= width ? str:new Array(width-str.length+1).join('0')+str;
//남는 길이만큼 0으로 채움
}
2. 문자열(String) 또는 숫자 (Number) 프로토타입 메서드로 구현
- 숫자 프로토타입으로 입력 길이만큼 앞에 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으로 채움
}
* 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로 뒤를 채움
}
728x90
'공부 > JavaScript' 카테고리의 다른 글
jQuery $.param() (0) | 2025.03.17 |
---|---|
[JavaScript] after() , insertAfter(), before(), insertBefore() (1) | 2025.01.26 |
[JavaScript] 소수점 처리 toFixed() (2) | 2025.01.24 |
[JavaScript] 삭제 remove(), detach(), empty(), unwrap() (0) | 2025.01.23 |
[JavaScript] 배열 find(), findIndex() (0) | 2025.01.23 |