//Google AdSense

문자열 객체

더보기

"text/어쩌구"  포매터 콘텐츠타입 mime-type 명시 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문자열 객체</title>
<script type="text/javascript">
	/*
		값에 의해 생성된 문자열 객체는 아래의 메서드 및 속성을 사용할 수 있다.
		var 변수 = '';
		var 변수 = new String();
		var 변수 = new String('');
		
		<String 객체의 메서드 및 속성>
			1.	변수.indexOf(''); - 변수값에 담긴 문자열을 indexOf의 인수값과 일치하는 인덱스 변호를 반환
				변수.lastIndexOf(''); - 변수값에 담긴 문자열을 lastIndexOf의 인수값과 일치하는 인덱스 번호를 뒤에서부터 반환
			2.	변수.replace('대상문자열', '바뀔 문자열') - replace의 첫번째 인수값과 일치하는 값을 두번째 인수값으로 치환
			3.	변수.substring(숫자1, 숫자2) - 문자열의 인덱스값 기준으로 substring의 첫번째 인수 부터 두번째 인수 전 까지 문자열을 잘라 반환
											인수값이 1개일 경우 인수값과 일치하는 인덱스 번호부터 출력
			4.	변수.length - (속성) 문자열의 개수를 반환
			5.	변수.split('구분자') - split 인수값 기준으로 잘라 배열로 반환
			6.	변수.toLowerCase() - 영문을 소문자로 변환
				변수.toUpperCase() - 영문을 대문자로 변환
			7.	변수.trim() - 문자열 처음과 끝의 공백 제거 (완전히 제거하려면 replace or 정규표현식 이용)
	*/
	
	//1. indexOf & lastIndexOf
	var str= '한국스마트정보교육원한국스마트정보교육원한국스마트정보교육원';
	console.log(str.indexOf('교육원'));
	console.log(str.lastIndexOf('교육원'));
	
	//2. replace
	var str = '한국스마트정보교육원';
	console.log(str.replace('한국', '전주한국'));
	
	//3. substring
	var str= '한국스마트정보교육원';
	str.substring(2,7);
	
	//4. length
	var str = '한국스마트정보교육원';
	console.log(str.length);
	
	//5. split
	var str= '한국-스마트-정보-교육원';
	console.log(str.split('-'));

	//6. toLowerCase & toUpperCase
	var str='abc';
	console.log(str.toUpperCase());
	console.log(str.toLowerCase());
	
	//7. trim
	var str= '          한 국  스 마 트  정 보    교 육 원      ';
	console.log(str.trim());
</script>

</head>
<body>

</body>
</html>

1. indexOf & lastIndexOf

2. replace

3. substring

4. length

5. split

6. toLowerCase & toUpperCase

7.  trim : 문자열 "앞&뒤"의 공백만 제거

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문자열 객체 실습 1</title>
<script type="text/javascript">
	/*
		실습 1. url 이라는 변수에 주소값이 담겨있다. url에 표현된 주소의 도메인명과 프로젝트명을 제외한 나머지 url만 출력시켜라.
			1.	도메인 - naver.com
			2.	프로젝트명 - myProject
			-완료시 출력될 url - myPage?name=홍길동&age=20
			-사용할 메서드 indexOf, substring
	*/
	var url = 'https://naver.com/myProject/myPage?name=홍길동&age=20';
	var proName = 'myProject/';
	url = url.substring(url.indexOf(proName)+proName.length);
	
	/*  
		실습2. url이라는 변수에 주소값이 담겨있다. 프로젝트명과 도메인을 제외한 주소값만 출력시켜라.
			-완료시 출력될 url - myPage?name=홍길동&age=20
			-사용할 메서드 lastIndexOf, substring
	*/
	var url = 'https://naver.com/myProject/myPage?name=홍길동&age=20';
	var a = '/';
	url = url.substring(url.lastIndexOf(a)+a.length);
	
	/*  
		실습3. url이라는 변수에 주소값이 담겨있다. 프로젝트명만 출력시켜라.
		-완료시 출력될 url - myProject
	*/
	
	var url = 'https://naver.com/myProject/myPage?name=홍길동&age=20';
	url = url.replace('https://','');
	url = url.replace('http://','');
	var slashArrUrl = url.split('/');
	url = slashArrUrl[1];
	
	
	url = url.replace('https://','');
	url = url.replace('http://','');
	var a = '/'
	var aI = url.indexOf(a);
	var aLi = url.lastIndexOf(a);
	url = url.substring(aI+a.length,aLi);
	
</script>
</head>
<body>

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>문자열 객체 실습 2</title>
<script type="text/javascript">
	/*  
		실습4. location의 객체를 활용하여 주소값을 가져오고 해당 주소값에 담긴 기능의 명칭을 출력하여라.
		(주소의 패턴 http://도메인/프로젝트/기능/페이지)
		도메인, 프로젝트명 고정
	*/
	
	//split
	var url = location.href;
	var a = '/';
	url = url.replace('http://'+location.host+a,'')
			.replace('https://'+location.host+a,'');
	
	var urlArr = url.split(a);
	url = urlArr[1];
	
	//substring
	var url = location.href;
	var a = '/';
	url= url.replace('http://'+location.host+a,'')
			.replace('https://'+location.host+a,'');
	url= url.substring(url.indexOf(a)+a.length, url.lastIndexOf(a))
	
	//substring2
	var url = location.href;
	var proName = 'javascriptEx06-0323';
	url= url.replace('https://'+location.host+'/','');
	url= url.replace('http://'+location.host+'/','');
	url= url.replace(proName+'/','');
	
	var len = url.indexOf('/');
	url = url.substring(0, len);
	console.log(url);
	
	
</script>
</head>
<body>

</body>
</html>

브라우저 객체 모델

window 객체

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>윈도우 객체</title>
<script type="text/javascript">
	//open
	window.open('https://naver.com','네이버','width=350,height=400, left=50, top=10, scrollbars=no');

	/*  
		setInterval() - 일정 시간 마다 함수를 실행시키는 메서드
		clearInterval() - 일정 시간 마다 실행되는 함수를 종료시키는 메서드
	*/
	
	var i = 0;
	var interval = setInterval(function(){
		console.log(i);
		if(i>10){
			clearInterval(interval);
		}
		i++;
	},3000);
    
    /*  
		setTimeout - 일정 시간이 지나면 코드를 실행하고 종료하는 메서드
	*/
	
	setTimeout(function(){
		console.log('3초 후 실행');		
	}, 3000);
	
</script>
</head>
<body>

</body>
</html>

 

 

open 메서드로 새 창을 생성한 모습

 

popupEx01.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>윈도우 객체 활용 팝업 실습</title>
<script type="text/javascript">
	/*
		실습5. 
			1.아래의 popupOpen 버튼 클릭시 팝업을 띄우시오.
			2.popupCall.html에서 팝업 닫기 버튼을 눌렀을 경우 팝업을 닫도록 하시오.
	*/
</script>

</head>
<body>
<button type="button" id="popupOpen">팝업띄우기</button>

<script type="text/javascript">
var popupOpen = document.getElementById('popupOpen');
popupOpen.addEventListener('click',function(){
	window.open('./popupCall.html','팝업창','width=400,height=600,left=50,top=50,scrollbars=no')
});
</script>

</body>
</html>

popupCall.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>띄운 팝업</title>
</head>
<body>
<button type="button" id="popupClose">팝업 닫기</button>
<script type="text/javascript">
	var popupClose = document.getElementById('popupClose');
	popupClose.addEventListener('click', function() {
		window.close();
	} )
</script>
</body>
</html>

setInterval메서드와 clearInterval메서드

 

 

setTimeout메서드. (자동으로 종료되기 때문에 clearTimeout은 잘 쓰지 않음)

 


DOM객체

DOM (Document Object Model) ①

DOM (Document Object Model) ② - event / 유효성검사

DOM (Document Object Model) ③ - style

 

 

location 객체 / history 객체

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>location / history 객체</title>
<script type="text/javascript">
	/*  
		<location>
		window 객체에 포함된 객체이며 url 주소에 대한 정보가 담겨있다.
		location.href - 주소값을 가지고 오거나 해당 주소로 이동시킨다.
		location.reload() - 현재 페이지를 갱신한다.
		
		<history>
		window 객체에 포함된 객체이며, 방문자의 이동 정보를 가지고있 다.
		history.back() - 이전 페이지로 이동
		history.go(숫자) - 인수값 만큼 현재 페이지 기준으로 방문 페이지 이동
		
	*/	
	
</script>

</head>
<body>

</body>
</html>

 

 

screen객체

 

screen과 client/offset의 속성값은 차이가 있다.

 

navigator 객체

 


javascript cookies

https://www.w3schools.com/js/js_cookies.asp

 

popupEx01.html에 쿠키추가

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>윈도우 객체 활용 팝업 실습</title>
<script type="text/javascript">
	/*
		실습5. 
			1.아래의 popupOpen 버튼 클릭시 팝업을 띄우시오.
			2.popupCall.html에서 팝업 닫기 버튼을 눌렀을 경우 팝업을 닫도록 하시오.
	*/
</script>

</head>
<body>
<button type="button" id="popupOpen">팝업띄우기</button>

<script type="text/javascript">

	var popupOpen = document.getElementById('popupOpen');
	popupOpen.addEventListener('click',function(){
		var cName = getCookie('popupCheck')
		if(cName != 'Y'){
			window.open('./popupCall.html','팝업창','width=400,height=600,left=20,top=20,scrollbars=no');
		}		
	});

	function getCookie(cname) {
		  var name = cname + "=";
		  var decodedCookie = decodeURIComponent(document.cookie);
		  var ca = decodedCookie.split(';');
		  for(var i = 0; i <ca.length; i++) {
		    var c = ca[i];
		    while (c.charAt(0) == ' ') {
		      c = c.substring(1);
		    }
		    if (c.indexOf(name) == 0) {
		      return c.substring(name.length, c.length);
		    }
		  }
		  return "";
		};

</script>

</body>
</html>

popupCall.html에 쿠키추가

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키를 활용하여 아이디 저장하기</title>
</head>
<body>
	<!--  
		실습6. 아이디 입력 후 '아이디 저장하기' 버튼 클릭시 쿠키로 아이디를 저장하고 새로고침 이후에도 아이디가 노출되도록 하시오.
	-->
	아이디 : <input type="text" id="userId" placeholder="아이디 입력">
	<button type="button" id="idSave">아이디 저장하기</button>
	
<script type="text/javascript">
	function setCookie(cname, cvalue, exdays) {
		  var d = new Date();
		  d.setTime(d.getTime() + (exdays*24*60*60*1000));
		  var expires = "expires="+ d.toUTCString();
		  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
		};
	
	function getCookie(cname) {
		  var name = cname + "=";
		  var decodedCookie = decodeURIComponent(document.cookie);
		  var ca = decodedCookie.split(';');
		  for(var i = 0; i <ca.length; i++) {
		    var c = ca[i];
		    while (c.charAt(0) == ' ') {
		      c = c.substring(1);
		    }
		    if (c.indexOf(name) == 0) {
		      return c.substring(name.length, c.length);
		    }
		  }
		  return "";
		};




	var idSave = document.getElementById('idSave');

	var savedId = '';
	
	idSave.addEventListener('click', function() {
		var userId = document.getElementById('userId');
		var userIdValue = userId.value;
		if(userIdValue != '' && userIdValue != undefined ){
			setCookie('userId',userIdValue,1);
		}		
	});
	
	var getUserId = getCookie('userId');
	if(getUserId != ''){
		var userId = document.getElementById('userId');
		userId.value = getUserId;
	};
	
	
</script>

</body>
</html>

input box value cookie

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키를 활용하여 아이디 저장하기</title>
</head>
<body>
	<!--  
		실습6. 아이디 입력 후 '아이디 저장하기' 버튼 클릭시 쿠키로 아이디를 저장하고 새로고침 이후에도 아이디가 노출되도록 하시오.
	-->
	아이디 : <input type="text" id="userId" placeholder="아이디 입력">
	<button type="button" id="idSave">아이디 저장하기</button>
	
<script type="text/javascript">
	function setCookie(cname, cvalue, exdays) {
		  var d = new Date();
		  d.setTime(d.getTime() + (exdays*24*60*60*1000));
		  var expires = "expires="+ d.toUTCString();
		  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
		};
	
	function getCookie(cname) {
		  var name = cname + "=";
		  var decodedCookie = decodeURIComponent(document.cookie);
		  var ca = decodedCookie.split(';');
		  for(var i = 0; i <ca.length; i++) {
		    var c = ca[i];
		    while (c.charAt(0) == ' ') {
		      c = c.substring(1);
		    }
		    if (c.indexOf(name) == 0) {
		      return c.substring(name.length, c.length);
		    }
		  }
		  return "";
		};




	var idSave = document.getElementById('idSave');

	var savedId = '';
	
	idSave.addEventListener('click', function() {
		var userId = document.getElementById('userId');
		var userIdValue = userId.value;
		if(userIdValue != '' && userIdValue != undefined ){
			setCookie('userId',userIdValue,1);
		}		
	});
	
	var getUserId = getCookie('userId');
	if(getUserId != ''){
		var userId = document.getElementById('userId');
		userId.value = getUserId;
	};
	
	
</script>

</body>
</html>

+ Recent posts