메타 문자
1) . : 모든 문자를 의미
2) a : 문자 a를 의미
3) a | b : a 또는 b를 의미
4) ^a : a로 시작
5) a$ : a로 끝
6) a* : a를 0번 이상 반복 (a가 없어도 좋음)
7) a+ : a를 1번 이상 반복 (a가 있어야 함)
8) a{n} : a를 n번 반복
9) a{n,} : a를 n번 이상 반복
10) a{n,m} : a를 n번 이상 m번 이하 반복
문자 클래스
대괄호 안에 묶여진 것은 모두 문자로 인식
1) [.] : 마침표(.)를 의미
2) [a] : 문자 a를 의미
3) [ab] : a 또는 b를 의미
4) ^[a] : a로 시작
5) [a]$ : a로 끝
6) [^a] : a를 제외
7) [0-9] : 숫자를 의미
8) [A-Z] : 대문자를 의미
9) [a-z] : 소문자를 의미
10) [가-힣] : 한글을 의미
이스케이프
1) \d : 숫자를 의미 (digit)
2) \D : 숫자가 아님
3) \w : 숫자, 영문, 밑줄을 의미 [0-9A-Za-z_] - 문자클래스 3번 방식으로 작성, '또는'으로 해석 (word)
4) \W : 숫자, 영문, 밑줄이 아님
<div>
<h1>핸드폰 번호 검사</h1>
<input type="text" id="mobile">
<input type="button" value="검사" id="btn_mobile_check">
</div>
<script>
/*
이벤트 대상 : 검사 버튼
이벤트 타입 : click
이벤트 리스너 : function(){ 입력된 핸드폰 번호 검사 }
*/
document.getElementById('btn_mobile_check').addEventListener('click',function(){
// 핸드폰 번호 검사 정규식 (010-숫자 4개-숫자 4개)
var regMobile = /^010-[0-9]{4}-\d{4}$/; //시작 끝 어떨지 지정하지 않으면 포함만 되어 있어도 맞다고 판단함
// 입력된 핸드폰 번호
var mobile = document.getElementById('mobile').value;
// 졍규식 체크
if(regMobile.test(mobile)){
alert('핸드폰 번호가 맞습니다')
} else {
alert('핸드폰 번호가 아닙니다')
}
})
</script>
[0-9]{4} : 메타문자로 숫자 4자리 표현
\d{4} : 이스케이프로 숫자 4자리 표현
<div>
<h1>비밀번호 검사하기</h1>
<input type="password" id="pw">
<input type="button" value="검사" id="btn_pw_check">
</div>
<script>
// 비밀번호 : 8~20자, 영문, 숫자, 특수문자 중 두가지 이상 포함
document.getElementById('btn_pw_check').addEventListener('click',function(){
var pw = document.getElementById('pw').value;
var validPwCount = /[A-Z]/.test(pw) // 대문자가 있으면 T
+ /[a-z]/.test(pw) // 소문자가 있으면 T
+ /[0-9]/.test(pw) // 숫자가 있으면 T
+ /^[A-Za-z0-9]/.test(pw); // 특수문자가 있으면 T
if(pw.length>8 && pw.length<=20 && validPwCount>=2){
alert('사용 가능한 비밀번호입니다')
} else {
alert('사용할 수 없는 비밀번호입니다')
}
})
</script>
<!-- history 객체 -->
<div>
<input type="button" value="뒤로" onclick="history.back()">
<input type="button" value="앞으로" onclick="history.forward()">
<input type="button" value="뒤로2번" onclick="history.go(-2)">
</div>
<!-- location 객체 -->
<div>
<input type="button" value="네이버" class="btn_link" data-site="naver">
<input type="button" value="구글" class="btn_link" data-site="google">
</div>
<script>
var btnLink = document.getElementsByClassName('btn_link');
for(let i = 0; i < btnLink.length; i++){
btnLink[i].addEventListener('click', function(){
var url;
switch(this.dataset.site){
case 'naver': url = 'https://www.naver.com/'; break;
case 'google': url = 'https://www.google.com/';break;
}
location.href = url;
})
}
</script>