쌍용교육센터 - 39일

개발자가 되고 싶어요 ㅣ 2024. 4. 12. 18:39

2024.04.12

 

정규표현식

<script>
	window.onload= function(){
		const form = document.getElementById('register_form');
		//이벤트 연결
		form.onsubmit = function(){
			const id = document.getElementById('id');
			/* 
			/패턴/ - > /(시작) 패턴 /(끝)
			^패턴의 시작
			[] '[' 와 ']' 사이의 문자들과 매치라는 의미
			[]안의 문자 사이에 하이픈(-)을 사용하게 되면 문자 사이의 범위(From-to)를 의미
			[a-zA-Z0-9] : a~z, A~Z, 0~9 를 의미
			{4,12} : 반복 횟수가 4~12번 사이
			$패턴의 끝
			*/
			/* if(!id.value.match(/^[a-zA-Z0-9]{4,12}$/)){ */
			if(!/^[a-zA-Z0-9]{4,12}$/.test(id.value)){
				alert('영문 또는 숫자 사용, 최소 4자 ~ 최대 12자');
				id.value = '';
				return false;
			}
		};
	};
</script>

 

웹 스토리지

웹 스토리지 API는 간단한 데이터를 사용자의 컴퓨터나 기기에 로컬로 저장하는 방법에 대한 표준을 정의한다.

 

로컬 스토리지

브라우저를 통해 사용자의 컴퓨터에 데이터를 지속적으로 저장할 수 있는 공간 다시 사이트를 방문했을 때 로컬 스토리지에 저장된 모든 데이터를 사용 가능

<script>
/* 
로컬 스토리지 : 브라우저를 통해 사용자의 컴퓨터에 데이터를 지속적으로 저장할 수 있는 공간
			다시 사이트를 방문했을 때 로컬 스토리지에 저장된 모든 데이터를 사용 가능
*/
window.onload = function(){
	const save = document.getElementById('save');
	const load = document.getElementById('load');
	
	
	//데이터 저장을 위한 이벤트 연결
	save.onclick = function(){
		const text = document.getElementById('text');
		//로컬 스토리지에 데이터 저장
		//첫번째 방법
		//localStorage.setItem('name',text.value);
		//두번째 방법
		localStorage.name = text.value;
		
		//입력창 초기화
		text.value='';
	};
	//저장된 데이터를 읽어오기 위한 이벤트 연결
	load.onclick = function(){
		//로컬 스토리지에 저장된 데이터 읽기
		//첫번째 방법
		//let loadedName = localStorage.getItem('name');
		//두번째 방법
		let loadedName = localStorage.name;
		
		alert('localStorage 객체에 저장된 이름 : ' + loadedName);
	};
};
</script>

 

JSON(JavaScript Object Notation)

<script>
window.onload = function(){
	const save = document.getElementById('save');
	//이벤트 연결
	save.onclick=function(){
		//사용자가 입력한 번호, 이름, 주소를 읽어옴
		const num = document.getElementById('num');
		const name = document.getElementById('name');
		const addr = document.getElementById('addr');
		
		//로컬 스토리지에 개별적으로 저장
		/* 
		localStorage.num = num.value;
		localStorage.name = name.value;
		localStorage.addr = addr.value;
		 */
		 
		//JSON(JavaScript Object Notation - 자바스크립트를 객체형식으로 만드는 것을 의미) 형식의 문자열로 만듬
		let memberStr = '{"num":' + num.value + ',"name":"' + name.value + '","addr":"' + addr.value + '"}';
		 
		//저장하기
		localStorage.member = memberStr; //meberStr에 저장된 문자열 저장
		 
		//입력창 초기화
		num.value='';
		name.value='';
		addr.value='';
	};
	
	const load = document.getElementById('load');
	//이벤트 연결
	load.onclick=function(){
		//저장된 문자열 읽어오기
		let loadedMemberStr = localStorage.member;
		//문자열을 객체로 변환
		const memberObj = JSON.parse(loadedMemberStr);
		//객체의 속성 호출
		alert(memberObj.num + ',' + memberObj.name+','+memberObj.addr);
	};
};
</script>

 

로컬 스토리지에 설정값 저장

<script>
	window.onload = function(){
		
		const bg_color = document.getElementById('bg_color');
		const text_color = document.getElementById('text_color');
		const text_size = document.getElementById('text_size');
		
		//초기값 설정
		load_setting();
		
		const myForm = document.getElementById('frm');
		//이벤트 연결
		myForm.onsubmit = function(event){
			//기본 이벤트 제거
			event.preventDefault();
			
			//데이터 저장
			save_setting();
			
		};
		
		//로컬 스토리지에 저장된 데이터 반환
		function load_setting(){
			bg_color.value = localStorage.getItem('bg_color');
			text_color.value = localStorage.getItem('text_color');
			text_size.value = localStorage.getItem('text_size');
			//스타일 반영
			apply_data();
		};
		//로컬 스토리지에 설정값 저장
		function save_setting(){
			localStorage.setItem('bg_color',bg_color.value);
			localStorage.setItem('text_color',text_color.value);
			localStorage.setItem('text_size',text_size.value);
			//스타일 반영
			apply_data();
		};
		//스타일을 태그에 반영
		function apply_data(){
			document.body.style.backgroundColor = bg_color.value;
			document.body.style.color = text_color.value;
			document.body.style.fontSize = text_size.value;
		};
	};
</script>

 

세션 스토리지

하나의 창이나 탭에 한정된 데이터를 보관할 수 있다. 사용자가 같은 사이트를 두 개의 창에서 접속하고 있더라도, 각 창은 자체적인 개별 세션 스토리지 객체를 가지며, 따라서 데이터를 별도로 유지하게 된다. 특정 사이트 접속해서 사용자 세션이 지속되는 동안만 세션 스토리지도 지속된다.

<script>
	/* 
	세션스토리지는 브라우저가 열려있는 동안 모든 데이터를 기억하고 있다가 탭(또는 창) 을 닫으면 모두 지워지는 저장 공간
	*/
	window.onload = function(){
		const save = document.getElementById('save');
		//이벤트 연결
		save.onclick=function(){
			const first = document.getElementById('first');
			//세션 스토리지에 저장
			//첫번째 방법
			/* sessionStorage.setItem('name',first.value); */
			sessionStorage.name = first.value;
			
			//저장된 데이터 읽기
			load();
		};
		//저장된 데이터 읽기
		function load(){
			const display = document.getElementById('display');
			//let name = sessionStorage.getItem('name');
			let name = sessionStorage.name;
			
			//저장된 값이 없으면 undefined 반환
			if(name){
				display.innerHTML = '저장된 값 : ' + name;
			}
		};
	}
</script>

 

File API

<script>
window.onload = function(){
	//파일을 선택할 때
	document.getElementById('file').onchange = function(){
		//선택한 파일의 file 객체 반환
		//input type="file" 태그에서 multiple="multiple" 속성을
		//명시하면 복수의 파일을 선택할 수 있고 그 정보는 배열에 저장됨.
		//따라서 하나의 파일을 선택해서 배열에 저장됨.
		const file = this.files[0];
		//선택한 파일의 이름출력
		alert(file.name + '을 선택하셨습니다.');
	};
	//읽기 버튼을 클릭할 때
	document.getElementById('btnStart').onclick = function(){
		readProcess();
	};
};
function readProcess(){
	//선택한 파일에 대한 정보 읽기, file 객체 반환
	const file = document.getElementById('file').files[0];
	
	if(!file){//if(file==undifined)
		alert('파일을 선택하세요!')
		return;
	}
	document.getElementById('filename').textContent = file.name;
	document.getElementById('filesize').textContent = '('+file.size+'bytes)';
	document.getElementById('filetype').textContent = file.type;
	document.getElementById('filedate').textContent = file.lastModifiedDate.toLocaleString();
	
	//select 태그 객체 반환
	const encodeList = document.getElementById('encoding');
	//선택한 인코딩 정보 반환
	let encoding = encodeList.value;
	
	const reader = new FileReader(); //파일 읽기 기능 제공
	reader.readAsText(file,encoding);///선택한 파일을 읽어서 문자열로 저장
	//파일의 내용을 모두 읽어들이면 onload 속성에서 대입된 함수가 호출됨
	reader.onload = function(){
		const contents = document.getElementById('contents');
		contents.value = reader.result;//읽어들인 내용 반환
	};
	reader.onerror=function(){
		alert('파일 읽기 중 오류 발생');
	};
}
</script>

'IT 국비 교육' 카테고리의 다른 글

쌍용교육센터 - 41일  (0) 2024.04.16
쌍용교육센터 - 40일  (0) 2024.04.15
쌍용교육센터 - 38일  (0) 2024.04.11
쌍용교육센터 - 37일  (0) 2024.04.09
쌍용교육센터 - 36일  (0) 2024.04.08