본문 바로가기
개발/javascript

[javascript] 문자열 길이 맞추기 padStart, padEnd

by 가시죠 2021. 1. 18.
반응형

padStart(전체길이, '추가문자열');

padEnd(전체길이, '추가문자열');

 

'1'.padStart(5, '0');   --> 00001

'10'.padStart(5,'0');  --> 00010

 

'1'.padEnd(3, '0');  --> 100

'10'.padEnd(3, '0');  --> 100

 

'1'.padStart(3);  -->    1 (1앞에 공백문자3개 추가)

 


공백문자를 활용한 디지털 시계 표현

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>디지털 시계</title>
    <style style="text/css">
		#text { font-size: 50px; font-weight: bold; }
	</style>
</head>
<body>
    <div id="text">
        <span class="hour"></span>
        : <span class="minute"></span>
        : <span class="second"></span>
    </div>
</body>
<script type="text/javascript">
    const hourEl = document.querySelector('.hour'); //시간
    const minuteEl = document.querySelector('.minute'); //분
    const secondEl = document.querySelector('.second'); //초
    update();

    function update() {
        const curTime = new Date();

        hourEl.innerText = String(curTime.getHours()).padStart(2,'0');
        minuteEl.innerText = String(curTime.getMinutes()).padStart(2,'0');
        secondEl.innerText = String(curTime.getSeconds()).padStart(2,'0');

        // 프레임에서 update() 재실행
        requestAnimationFrame(update);
    }
</script>
</html>
반응형

댓글