자리수 만큼 남는 공간을 0으로 채우는 방법

Hyunwoo Seo·2022년 9월 14일
0

JavaScript

목록 보기
12/31
post-thumbnail

숫자를 웹상에 문자로 표현을 할 때, 자리수만큼 앞에 0을 채워야 하는 경우가 있다.

문자열(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으로 채움
}

//문자열 프로토타입으로 입력 길이만큼 앞에 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"

0개의 댓글

Powered by GraphCDN, the GraphQL CDN