2023. 4. 27. 20:00ㆍJavaScript
HTML5
DisplayVisibility09.html
9. 보이기 안 보이기 속성
diplay와 visibility속성은 레이어(div)보였다 안보였다
할수 있게 하는 CSS속성(div 뿐만 아니라 모든 태그에 적용됨)
visibility: visible(보이게)
hidden(안보이게) ==> 영역은 그대로 레이어가
사라짐
display: block
inline-block
none(안보이게) ==> 영역도 레이어도 사라짐
disply:none
※-인라인->블락으로 block:(인라인을 블락으로)
-블락->인라인으로 inline(블락엘리먼트를 인라인엘리먼트로 만듦)
-블락->블락인데 배치는 가로 배치로 inline-block
DisplayVisibility09.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DisplayVisibility09.html</title>
<style>
fieldset {
width:400px;
}
fieldset div{
width: 50px;
height: 50px;
}
.inline > div{
/*div가 가로배치되고 inline 요소으로 바뀜*/
display:inline;/*안라인 블락 엘리먼트로 바뀜 html5의 속성 hidden과 같다*/
}
.inline-block > div{
/*가로배치되나 block 요소는 그대로 유지됨. 높이가 content로 바뀌지 않음*/
display: inline-block;
}
.block > span{
/*인라인 엘리먼트를 블락엘리먼트로 바뀜*/
display: block;
}
</style>
</head>
<body>
<h2>display 및 visibility속성</h2>
<div>
<h3>visibility</h3>
<fieldset class="visible">
<legend>visibility:hidden일때 영역은 그대로 존재</legend>
<div style="background-color:red;">left</div><!--div는 블락 엘리먼트-->
<div style="background-color:green;visibility: hidden;">center</div><!--사라졌지만 영역은 그대로-->
<div style="background-color:blue;">right</div>
</fieldset>
<h3>display</h3>
<fieldset class="visible">
<legend>display:none일때 영역도 사라짐</legend>
<div style="background-color:red;">left</div>
<div style="background-color:green;display: none;">center</div><!-- css속성:display// 사라졌는데 영역도 사라짐-->
<div style="background-color:blue;">right</div>
</fieldset>
<h3>HTML5의 hidden속성</h3>
<fieldset class="visible">
<legend>태그의 hidden 속성으로 CSS의 diplay:none효과</legend>
<div style="background-color:red;">left</div>
<div style="background-color:green;" hidden >center</div><!--html5 속성으로 사라짐-->
<div style="background-color:blue;">right</div>
</fieldset>
<h3>block->inline</h3>
<fieldset class="inline">
<legend>가로배치로 변경</legend>
<div style="background-color:red;">left</div>
<div style="background-color:green;">center</div>
<div style="background-color:blue;">right</div>
</fieldset>
<h3>block->inline-block</h3>
<fieldset class="inline-block">
<legend>가로배치로 변경</legend>
<div style="background-color:red;">left</div>
<div style="background-color:green;">center</div>
<div style="background-color:blue;">right</div>
</fieldset>
<h3>inline->block</h3>
<fieldset class="block">
<legend>세로배치로 변경</legend>
<span style="background-color:red;">left</span><!--span은 인라인 엘리먼트임-->
<span style="background-color:green;">center</span>
<span style="background-color:blue;">right</span>
</fieldset>
</body>
</html>
결과)
//////DisplayVisibility09.html
FloatClear10.html
10. DIV배치 관련 속성
float:레이어(div태그)의 위치 지정
left,right
앞선 레이어의 영향을 받는다
박스의 크기가 인라인 엘리먼트처럼 콘텐츠
크기로 줄어든다.
clear:float의 효과를 무력화 시킨다
left,right,both
FloatClear10.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FloatClear10.html</title>
</head>
<body>
<fieldset>
<legend>float속성(div의 width미 지정)</legend>
<div style="background-color:red;float: left;">div1</div><!--div 블락 엘리먼트,float을 주면 가로 미지정지 content크기만큼,초록색은 나머지 영역으로 흘러들어옴(다채움)-->
<div style="background-color:green;float: right">div2</div><!--우측으로 가고 가운데 공간을 아래 블루가 채움 -->
<div style="background-color:blue;clear:both;">div3</div><!--나머지 부분을 clear float효과 무효과-->
</fieldset>
<!-- div의 width미정시에는 나머지 여유 공간을
채운다 단,width 지정시에는 자동으로
여유 공간을 채우지 않는다 따라서
배치를 위해서는 반드시 float속성의 left/right로
배치하자.그러면 남은 영역의 왼쪽/오른쪽등을 채우게 된다
-->
<fieldset>
<legend>float속성(div의 width 지정)</legend>
<div style="background-color:red;width:100px;float: left;">div1</div><!--div 블락 엘리먼트, 높이 지정-->
<div style="background-color:green;width: 100px;float: left;">div2</div><!--div바로 왼쪽에 붙임-->
<div style="background-color:blue;width:100px;">div3</div>
</fieldset>
<!--
height도 지정시에는 배치시에
모든 DIV에 float나 clear속성을 부여해라
-->
<fieldset>
<legend>float속성(div의 width/height 지정)</legend>
<div style="background-color:red;width:50px;height:50px;float:left">div1</div><!--div 블락 엘리먼트, 높이 지정,너비 지정-->
<div style="background-color:green;width:50px;height:50px;float: left;">div2</div>
<div style="background-color:blue;width:50px;height:50px;clear: both;">div3</div><!--나머지 부분을 clear float효과 무효과, 아래에 만약 div있으면 무효과 받으면서 됨-->
</fieldset>
</body>
</html>
결과)
//////////FloatClear10.html
PositionTopLeft11.html
10. DIV배치 관련 속성
position:레이어의 위치지정
absolute:절대위치-웹브라우저 좌측 상단(0,0)을
기준으로 위치 지정
relative:상대위치-레이어안의 레이어가 바깥쪽
레이어를 기준으로 위치지정
위는 바깥 div기준임
※단,안쪽 div는 무조건 바깥 div를 기준으로
배치된다.안쪽 div는 absolute를 주든 relative를 주든
바깥 div가 기준이 된다.
또한 안쪽에 여러개의 div를 연속으로 배치한 경우
absolute를 준 경우 바깥 div가 0,0을 기준으로
배치되고 relative를 준경우
먼저 배치된 안쪽 div의 좌측 하단을 기준으로 상대적으로 배치가 된다.
top:y좌표
left:x좌표
zindex:레이어의 위치 지정, 값이 높을 수록 레이어가
위에 떠 있다.
레이언 안의 레이어는 z-index속성이 의미 없다.
왜냐하면 레이안의 레이어가 바깥 레이어 보다
항상 위에 떠 있다.
※ 레이어의 크기(width)지정시에는 float의
left,right값으로 위치를 지정하고
width미지정시에는 float의 영향을 받아
빈 영역에 div가 위치한다.
※ 바깥 div는 안쪽 div보다 항상 밑에 떠 있다
고로 z-index로 바깥 div를
안쪽 div보다 위에 뜨게 할 수 없다
PositionTopLeft11.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PositionTopLeft11.html</title>
</head>
<body>
<!--
position:static 기본값으로 left,top의 영향을 받지 않는다
※원칙]부모 요소에 position속성(absolute 혹은 relative)을 주면 자식은
무조건 부모요소를 기준으로 한다.즉 부모 영역의 왼쪽 상단이 오프셋(0,0)이다
position이
absolute:브라우저 상단(body가 부모인 경우) 혹은 부모를 기준으로 left,top좌표가 결정됨
relative:원래 자리한 위치를 기준으로 left,top좌표가 결정됨
-->
<!--
<fieldset>
<legend>부모가 position:absolute 인 경우</legend>
<div style="background-color:yellow;position: absolute;">
<div style="background-color:red;width:50px;height:50px; left:100px;top:100px;position: absolute;">자식1</div><!--부모의 position이 없으니 body기준0,0-->
<!--<div style="background-color:green;width:50px;height:50px; left:150px;top:150px;position: absolute;">자식2</div>
<div style="background-color:blue;width:50px;height:50px;left:200px;top:200px;position: absolute;">자식3</div>
</div>
</fieldset>
-->
<!--
<fieldset>
<legend>부모가 position:relative 인 경우</legend>
<div style="background-color:yellow;position: relative;left:50px;top:50px">
원래 위치가 기준점(0,0)이 된다
<div style="background-color:red;width:50px;height:50px;left:100px;top:100px;position:relative">Child1</div>
<div style="background-color:green;width:50px;height:50px;left:150px;top:150px;position:relative">Child2</div>
<div style="background-color:blue;width:50px;height:50px;left:200px;top:200px;position:relative">Child3</div>
</div>
</fieldset>
-->
<!--
<fieldset>
<legend>부모에 position을 안 준 경우</legend>
<div style="background-color:yellow;">
브라우저 왼쪽 상단이 오프셋이 된다
<div style="background-color:red;width:50px;height:50px;position: absolute;left:100px;top:100px">차일드1</div>
<div style="background-color:green;width:50px;height:50px;position: relative;left:150px;top:150px">차일드2</div>
브라우저 왼쪽 상단이 오프셋이 된다
<div style="background-color:blue;width:50px;height:50px;position: absolute;left:200px;top:200px">차일드3</div>
</div>
</fieldset>
-->
<fieldset>
<legend>Z-INDEX속성</legend>
<div style="background-color:yellow;width:300px;height:300px; position: relative;">
<div style="background-color:red;width:100px;height:100px;position: absolute;left: 20px;top: 20px;z-index: 10;">div1</div>
<div style="background-color:green;width:100px;height:100px;position: absolute;left: 60px;top: 60px;z-index: 8;">div2</div>
<div style="background-color:blue;width:100px;height:100px;position: absolute;left: 100px;top: 100px;z-index: 9;">div3</div>
</div>
</fieldset>
<h2>버튼 클릭시 div를 특정 위치에 띄우기</h2>
<div id="parent" style="min-width:25em;margin-bottom:10px;background-color:rgb(109, 146, 15);width:100%;height:300px;position: relative;">
<div id="child" style="text-align:center;line-height:100px;background-color:rgb(231, 225, 116);width:50%;height:100px;position: absolute;display: none;">
나이를 입력 :<input type="text"/>
</div>
</div>
<button>입력창 띄우기</button>
<script>
var child=document.querySelector('#child');
var parent=child.parentElement;//var parent=document.querySelector('#parent');
var button=parent.nextElementSibling;//var button=document.querySelector('button');
console.log(screen.availWidth);//해상도1980x1080
console.log(parent.style.width);//100%
//console.log(button);//가져왔나 체크용
//자식 div를 띄울 고정 좌표 위치(left,top) 구하기 - 브라우저 크기를 줄이는 경우
//정 가운데 배치가 안된다(오프셋이 고정되서:좌표를 px로 줘서)
/*
console.log(screen.availWidth);//해상도 1920 X 1080
console.log(parent.style.width);//100%
console.log((parseInt(parent.style.width)/100)/2);
var parentWidth=screen.availWidth*(parseInt(parent.style.width)/100)/2;
var leftChild = parentWidth-parentWidth/2;
var topChild = parseInt(parent.style.height)/2 - parseInt(child.style.height)/2;//정중앙에서 자식 너비 절반 뺴기
console.log('left:%s,top:%s',leftChild,topChild);//left:480,top:100*/
button.onclick=function(){
/*
//left:100px,top:100px위치에 띄우기
//child.style.left = 100+'px';
//child.style.top = 100+'px';
//정가운데 띄우기
child.style.left = leftChild+'px';
child.style.top = topChild+'px';*/
//고정좌표로 하지 않고 해상도에 따라 오프셋 위치를 변하도록(반응형)
//수평으로 가운데 정렬
parent.style.display='flex';
parent.style.justifyContent='center';
//수직으로 가운데
parent.style.alignItems="center";
//브라우저를 스마트폰 해상도 크기로 줄일시 입력 텍스트 상자가 밑으로 흘려내려가는거
//방지하기 위한 자식DIV의 최소폭 지정
child.style.minWidth="288px";
child.style.display='block';
};
</script>
</body>
</html>
결과)
////////////////PositionTopLeft11.html
Flex12_1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flex12_1.html</title>
<style>
.item{
background-color: green;
border:2px red solid;
box-sizing: border-box;
}
.container1{
background-color: yellow;
display:flex;/*블락 엘리먼트 특성을 가진 컨테이너 생성:즉 가로폭이 부모 영역 전체차지*/
}
.container2{
background-color: pink;
/* 인라인 엘리먼트 특성을 가진 컨테이너 생성.
컨테이너의 영역이 아이템들의 영역에 맞게 줄어든다:*/
display: inline-flex;
}
.container3{
background-color: yellow;
display: flex;
/*flex-direction: row;기본값*/
/*flex-direction: row-reverse;시작선이 오른쪽 끝이 된다*/
/*flex-direction: column;주축이 블록방향 div와 같음*/
flex-direction: column-reverse;/*시작선이 아래쪽 끝이 된다*/
}
.container4{
background-color: yellow;
display: flex;
/*flex-wrap: nowrap;기본값*//*브라우저크기를 줄이면서 테스트*/
/*flex-wrap: wrap;행이 아래로 나열된다*/
/*flex-wrap: wrap-reverse;행이 위로 나열된다*/
/*축약 속성:flex-direction flex-wrap(row nowrap이 기본값)*/
flex-flow:row-reverse wrap ;
}
.container5{
background-color: yellow;
display: flex;/*inline-flex일때는 적용불가(여유공간이 없으니까)*/
/*justify-content:flex-start ;기본값*//*왼쪽 정렬과 같다*/
/*justify-content:flex-end;오른쪽 정렬과 같다*/
/*ustify-content:center;가운데 정렬과 같다*/
/*첫번째 아이템은 시작선,마지막은 끝선에 붙고 여유공간을 아이템 사이에 균등배분해서 정렬*/
/*justify-content: space-between;*/
/*아이템들의 주변(around)에 균일한 간격을 배분해서 정렬*/
/*justify-content: space-around;*/
/*여유 공간을 아이템간 및 시작선 및 끝선에 모두 균등하게 배분해서 정렬-IE는 미지원*/
justify-content: space-evenly;
}
.container6{
background-color: yellow;
display: flex;
/*테스트시 교차축 방향으로 크기를 적당히 주자*/
height: 150px;
/*align-items: stretch;기본값*//*아이템들을 교차축방향으로 늘려 컨테이너를 가득 채운다*/
/*교차축의 시작선을 기준으로 아이템들을 정렬-세로폭은 컨텐츠 크기만큼(위쪽 정렬)*/
align-items:flex-start ;
/*교차축의 끝선을 기준으로 아이템들을 정렬.-세로폭은 컨텐츠 크기만큼(아래쪽 정렬)*/
/*align-items:flex-end ;*/
/*교차축 방향으로 가운데 정렬 */
/*align-items: center;*/
/*justify-content: center;정 가운데 정렬시 추가*/
/*글꼴의 기준선인 baseline을 기준으로 아이템들을 정렬-글꼴 크기를 다르게 하여 테스트*/
/*align-items: baseline;*/
}
.container7{
background-color: yellow;
display: flex;
flex-flow:row wrap;
height: 150px;
/*flex-wrap: wrap;이 설정된 상태에서, 아이템들의 줄이 2줄 이상 되었을 때의
교차축을 따라 아이템들을 정렬하는 방식을 지정
속성값은 justify-content와 동일
아이템들이 한 줄일 경우 align-items 속성 사용
즉 wrap일때는 교차축 정렬은 align-content를 사용하자
*/
/*여러행일때 align-items 사용시*/
/*여러행 사이에 남은 여백을 동일하게 배분한다*/
/*align-items:flex-start ; */
/*align-items:center ;*/
/*align-content:flex-start ;위의 align-items:flex-start와 비교해 보자*/
/*여러행일때 align-content 사용시*/
/* space-XXX속성이 아닌 속성 즉 flex-start,flex-end,center적용시
줄 사이에 여백이 없다*/
/*align-content:stretch;기본값*/
/*align-content: flex-end;여러행이 여백없이 묶여서 아랫쪽 정렬*/
align-content:center ;/*여러행이 여백없이 묶여서 가운데 정렬*/
/*행이 컨텐츠가 되서 행과 행사이는 동일한 여백. 시작선에는 첫행이 붙고 끝선에는 마지막행이 붙는다*/
/*align-content: space-between;*/
/*align-content: space-around;각 행 주위의 좌우 여백이 모두 동일*/
/*align-content: space-evenly;행과 행사이 및 시작선과 끝선과의 여백도 모두 동일*/
}
</style>
</head>
<body>
<fieldset>
<legend><h2>Flex Container의 display속성</h2></legend>
<div class="container1" >
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
</div>
<hr/>
<div class="container2" >
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
</div>
</fieldset>
<fieldset>
<legend><h2>Flex Container의 flex-direction속성</h2></legend>
<div class="container3">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
</div>
</fieldset>
<fieldset>
<legend><h2>Flex Container의 flex-wrap속성</h2></legend>
<div class="container4">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item">item10</div>
</div>
</fieldset>
<fieldset>
<legend><h2>Flex Container의 justify-content속성(주축방향 정렬)</h2></legend>
<div class="container5" style="height:150px">
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item">item10</div>
</div>
</fieldset>
<fieldset>
<legend><h2>Flex Container의 align-items속성(교차축방향 정렬-한줄일때)</h2></legend>
<div class="container6">
<div class="item" style="font-size:.5em">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item" style="font-size:2em">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item" style="font-size:.5em">item10</div>
</div>
</fieldset>
<fieldset>
<legend><h2>Flex Container의 align-content속성(교차축방향 정렬-여러줄일때)</h2></legend>
<div class="container7">
<div class="item" style="font-size:.5em">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item" style="font-size:2em">item5</div>
<div class="item">item6</div>
<div class="item">item7</div>
<div class="item">item8</div>
<div class="item">item9</div>
<div class="item">item10</div>
<div class="item">item11</div>
<div class="item">item12</div>
<div class="item">item13</div>
<div class="item">item14</div>
<div class="item" style="font-size:.5em">item15</div>
</div>
</fieldset>
</body>
</html>
/////////////Flex12_1.html
JavaScript
BOM2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BOM10_2.html</title>
<script>
console.log(window.location);
console.log(location.href);
console.log(location.protocol);
console.log(location.port);
console.log(location.hostname);
//location.href="https://www.nate.com";//사용자 이벤트(클릭)에 의하지 않고 자동으로 이동 - 뒤로가기 활성화(이전히스토리)
//location.replace("https://www.nate.com");//사용자 이벤트(~~~~)
//location.reload();//열면 계속 요청이라 무한반복
function fnLogin(){
//가정]아이디가 "KIM"이고 비번이 "1234"인 경우 회원이라고 가정하자
//회원이면 마이페이지(DOM9_4.html)로 자동으로 이동시키자.
var username = document.querySelector('#user').value;
var password = document.querySelector('#pass').value;
if(username==='KIM' && password==='1234'){
//location.href='DOM09_4.html';
location.replace('DOM09_4.html');
}
else{
//location.href='DOM09_5.html';
location.replace('DOM09_5.html');
}
}
console.log(history);
console.log(navigator);
console.log(navigator.geolocation)?'현 브라우저는 Geolocation API지원':'Geolocation API 미 지원';
console.log(navigator.storage)?'현 브라우저는 스토리지 API지원':'스토리지 API 미 지원';
console.log(navigator.userAgent);
console.log(window.screen);
console.log(screen.availWidth);//이용가능한 모니터 가로 해상도(트레이바 제외)
console.log(screen.availHeight);//이용가능한 모니터 세로 해상도(트레이바 제외)
console.log(screen.width);//모니터 가로 해상도
console.log(screen.height);//모니터 세로 해상도
//아래는 브라우저의 body내용이 뿌려지는 영역의 가로/세로 크기
window.onresize=function(){
console.log('가로폭:',window.innerWidth);//바디에 뿌려지는 크기console에서 확인
console.log('세로폭:',window.innerHeight);
}
</script>
</head>
<body>
<h2>location & history & navigator & screen객체</h2>
<fieldset>
<legend>BOM 객체의 함수 혹은 속성 테스트</legend>
아이디 <input type="text" id="user" />
비밀번호 <input type="password" id="pass" />
<input type="button" value="로그인" onclick="fnLogin();" />
<input type="button" value="새로고침" onclick="location.reload();"/>
<input type="button" value="history테스트(href)" onclick="location.href='BOM10_1.html'"/>
<input type="button" value="다음 페이지" onclick='history.go(1)'/>
<input type="button" value="이전 페이지" onclick='history.back()'/>
<input type="button" value="웹브라우저 종류" onclick="console.log(navigator.userAgent);" />
</fieldset>
<script>
//이전 페이지 URL얻기:document.referrer
//단.history객체의 함수(go()/back())로 페이지 이동시
//document.referrer는 빈 문자열
//※이전 페이지의 URL이 필요한 경우 반드시 그때는 location객체의
// href로 이동하자.
console.log('이전 페이지 URL:',document.referrer);
</script>
</body>
</html>
결과)
로그인시 DOM09_5.html으로 이동 근데 replace라 히스토리가 없음
history테스트(href) 클릭 시 href로 이동이라 히스토리가 있음
이전페이지 가져오는 속성: document.referrer
/////BOM2.html
String11.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String11.html</title>
<script>
var str1="안녕 자바스크립트!";//문자열 리터럴로 string객체 생성
var str2="Hello JavaScript!";
var str3='Hi JS!';
var str4 = new String('Hi JS!');//new 생성자함수()로 string객체 생성
console.log(typeof str1,typeof str4);//string object
console.log('%O',str1);//안녕 자바스크립트!
console.log('%O',str4);//▶String
console.log(str1.toString())//안녕 자바스크립트!
console.log(str4.toString())//Hi JS!
console.log(str1 instanceof String);//false 이유?//문자열 리터럴로 만든것이라서
console.log(str4 instanceof String);//true 이유?//생성자 함수여서
//인덱스로 접근해서 문자열을 구성하는 하나의 문자를 추출가능.
//자바는 char[] String객체.toCharArray()호출후 가능
//인덱스를 키로해서 문자열이 저장 되어있다(배열처럼)즉 유사 배열이다
console.log(str1[0]);
var str1Arr=Array.from(str1);//유사배열을 배열로 변경
str1Arr.forEach((item,index)=>{
console.log('%d번째 요소:%s',index,item);
});
//1]문자열의 길이 얻기-length 속성
console.log('str1의 길이:',str1.length);
console.log('str4의 길이:',str4.length);
//2]문자열 객체의 함수를 이용해서 텍스트 꾸미기
document.write('<h2>함수로 텍스트 꾸미기</h2>');
console.log('볼드체(함수):',str1.bold());
document.write('볼드체(함수):',str1.bold());
document.write('<br/>볼드체(태그):<b>',str1+"</b>");
document.write('<br/>이탤릭체(함수):',str1.italics());
document.write('<br/>이탤릭체(태그):<i>',str1+"</i>");
document.write('<br/>가운데 선긋기(함수):',str1.strike());
document.write('<br/>가운데 선긋기(태그):<strike>',str1+"</strike>");
var url='https://www.nate.com';
console.log('링크걸기(함수):'+str1.link(url));
document.write('<br/>링크걸기(함수):',str1.link(url));
document.write('<br/>링크걸기(태그):<a href='+url+'>',str1+"</a>");
//3]대소문자 변경
console.log('대문자로 변경:',str2.toUpperCase());
console.log('소문자로 변경:',str2.toLowerCase());
//4]특정 위치(인덱스)의 하나의 문자 얻어오기
//charAt(인덱스):인덱스는 0부터 시작
console.log(str3.charAt(3));
console.log('자바스크립트'.charAt(3));
//5]문자열에서 특정 문자열 얻어오기 substring(시작인덱스,끝인덱스): 끝인덱스 -1
console.log('ACADEMY'.substring(3,7));
//5-1]문자열에서 특정 문자열 얻어오기2 -substr(시작인덱스,문자열갯수)
console.log('ACADEMY'.substr(3,4));
//6]특정 위치의 아스키 코드값 가져오기 charCodeAt(인덱스) :자바에서는 codePointAt(int index)
console.log('ACADEMY'.charCodeAt(3));
console.log('ACADEMY'.codePointAt(3));
//7]특정 코드값을 문자로 변환(클래스 메소드):String.fromCharCode(코드값)
console.log(String.fromCharCode(68));
console.log(String.fromCodePoint(68));
/*
※String객체는 문자 하나 하나가 배열형태 처럼로 저장됨.
예]var str="AB가C";
str[0]="A"
str[1]="B"
str[2]="가"
str[3]="C" 형태로 저장됨.
var str="AB가C"; 는 1]그리고 2]처럼 접근할수 있다 즉 유사배열이다
//1]
var str= new Array(4);
str[0]="A"
str[1]="B"
str[2]="가"
str[3]="C"
//2]
var str = ["A","B","가","C"];
*/
for(var i=0;i < str1.length;i++){
console.log('%d번째 요소:%s',i,str1[i]);
}
//8]구분자로 문자열 분리-배열 반환
// split(구분자[정규표현식][,limit])
// ※만약 해당 구분자가 없으면 무조건 배열크기가
// 1인 배열에 문자열 전체가 저장됨.
var tel ='010.1234.5678';
//var arr= tel.split('.');//.을 구분자로 사용.즉 자바처럼 정규표현식의 .으로 처리 안함
//var arr = tel.split('.',2); //2개로 배열의 요소수를 제한
//var arr = tel.split(/./g); //이때 /./은 임의의 한 문자(정규 표현식)
var arr = tel.split(/\./g);//tel.split('.');와 ㄱ타다
console.log(arr);
//9]특정 문자열의 인덱스값 알아내기
//indexOf("찾는 문자열"):찾는 문자열이 존재하면
// 찾는 문자열의 시작인덱스 값 반환
// 존재하지 않으면 -1 반환.
console.log('ACADEMY'.indexOf('A'));//0
console.log('ACADEMY'.indexOf('CAD'));//1
console.log('ACADEMY'.indexOf('cad'));//-1
//9-1]특정문자열의 인덱스값 알아내기2
// lastIndexOf("문자열"):반환값은 indexOf()와 동일
console.log('ACADEMY'.lastIndexOf('A'));//2
console.log('ACADEMY'.lastIndexOf('CAD'));//1
console.log('ACADEMY'.lastIndexOf('cad'));//-1
//10]양쪽 공백제거:trim()
console.log('X'+' H E Y '+'Y');
console.log('X'+' H E Y '.trim()+'Y');
/*
문]
문자열을 매개변수로 받는 함수로,
받은 인자가 숫자형식이 아니면 false반환
숫자형식이면 true를 반환하는 함수를 정의해라.
그리고 호출해서 결과 확인해라...
//"12A"->false ,"가100"->false, "99"->true
*/
function isNumber(str){
if(isNaN(Number(str))) {
return false;
}
return true;
}
console.log(isNumber("12A"));
console.log(isNumber("가100"));
console.log(isNumber("99"));
/*
아래 이메일 주소에서 @와 .사이에 있는 값만 얻어 오자
*/
var emails=['kim@naver.com','park@cyworld.com','lee@nate.com'];
//문]배열을 매개변수로 받아서 가운데 도메인만 얻어서
// 출력하는 함수를 정의하고 함수를 호출하자.
function getEmails(emails){
var result=[];
for(var i=0; i<emails.length; i++){
var email=emails[i];//하나씩 뽑음
var atIndex=email.indexOf('@');//해당 인덱스 번호 뽑음
var dotIndex=email.lastIndexOf('.');//해당 인덱스 번호 뽑음
if(atIndex >=0 && dotIndex > atIndex){
var domain=email.slice(atIndex +1, dotIndex);
result.push(domain);
}
}
return result;
}
console.log(getEmails(emails));
</script>
</head>
<body>
</body>
</html>
결과)
////////String11.html
'JavaScript' 카테고리의 다른 글
39일차 2023-05-01 (0) | 2023.05.02 |
---|---|
38일차 2023-04-28 (0) | 2023.05.01 |
36일차 2023-04-26 (0) | 2023.04.26 |
35일차 2023-04-25 (0) | 2023.04.25 |
34일차 2023-04-24 (0) | 2023.04.24 |