본문 바로가기
JAVASCRIPT

JAVASCRIPT | 문자열 메서드 | padStart( ) / padEnd( )

by 코딩하자9 2022. 8. 17.
728x90

padStart() / padEnd()에 대해 알아보자 !

String.prototype.padStart( );
주어진 길이에 맞게 앞의 문자열을 채우고, 새로운 문자열을 반환해주는 메서드입니다.
String.prototype.padEnd( );
주어진 길이에 맞게 뒤의 문자열을 채우고, 새로운 문자열을 반환해주는 메서드입니다.


construction(구문)

"str".padStart(targetLength [,padString]);

targetLength(문자열 길이 지정)

문자열의 길이를 지정해줍니다. 현재 길이보다 작다면 있는 그대로 반환시켜줍니다.

padString(채워넣을 다른 문자열)

채워 넣는 문자열이 지정해준 문자열의 길이를 넘어서면 좌측부터 순서대로 넣고 뒷부분은 자릅니다.

# 예제를 통해 익혀봅시다.

const str1 = "456";

const currentStr1 = str1.padStart(1, "0");
const currentStr2 = str1.padStart(2, "0");
const currentStr3 = str1.padStart(3, "0");
const currentStr4 = str1.padStart(4, "0");
const currentStr5 = str1.padStart(5, "0");
const currentStr6 = str1.padStart(6, "0");
const currentStr7 = str1.padStart(6, "1");
const currentStr8 = str1.padStart(6, "12");
const currentStr9 = str1.padStart(6, "123");
const currentStr10 = str1.padStart(6, "1234");
const currentStr11 = str1.padStart(6);
결과보기
456
456
456
0456
00456
000456
111456
121456
123456
123456
___456(앞부분 공백처리)
const str1 = "456";

const currentStr12 = str1.padEnd(1, "0");       //456
const currentStr13 = str1.padEnd(2, "0");       //456
const currentStr14 = str1.padEnd(3, "0");       //456
const currentStr15 = str1.padEnd(4, "0");       //4560
const currentStr16 = str1.padEnd(5, "0");       //45600
const currentStr17 = str1.padEnd(6, "0");       //456000
const currentStr18 = str1.padEnd(6, "1");       //456111
const currentStr19 = str1.padEnd(6, "12");      //456121
const currentStr20 = str1.padEnd(6, "123");     //456123
const currentStr21 = str1.padEnd(6, "1234");    //456123
const currentStr22 = str1.padEnd(6);            //456___
결과보기
456
456
456
4560
45600
456000
456111
456121
456123
456123
456___(뒷부분 공백처리)

댓글


It's cording time

코딩 여기서 정리하고 배워보자구 :9

광고 준비중입니다.