kimmgamjja

[JavaScript] 자리수 남은 만큼 0으로 채우기 pad 본문

공부/JavaScript

[JavaScript] 자리수 남은 만큼 0으로 채우기 pad

인절미댕댕이 2025. 1. 25. 08:00
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로 뒤를 채움
}

 

 

https://blogpack.tistory.com/600

728x90