[JavaScript] test() / 한글, 영어, 숫자만 입력 받기(정규표현식)

GXXN_YX·2023년 2월 21일
0
post-thumbnail

과제 진행 도중 한글 1자리만 입력되도록 조건을 걸어야 하는 상황이 생겼다.

조건을 수행하기 위하여 자바스크립트에서 문자열을 입력받을 때 한글, 영어, 숫자만 입력받을 수 있도록 하는 방법에 대하여 알아보았다.


💡 정규표현식(regex)을 이용하면 입력받은 문자열이 한글, 영어, 숫자로만 구성되었는지 확인할 수 있다. 어떻게 구현하는지 알아보자.

📌 1. 문자열에 한글, 영어, 숫자만 있는지 확인

정규표현식(regex)은 /pattern/flag로 표현하며, test(string) 함수는 인자로 전달된 문자열정규표현식의 패턴일치하면 true를 리턴하며 그렇지 않으면 false를 리턴합니다.

아래 예제와 같이 정규표현식을 구성하면, 문자열에 한글, 영어, 숫자만 있을 때 true를 리턴합니다. 패턴에 사용된 표현식의 의미는 아래와 같습니다.

^ : 문자열의 시작을 의미
[ㄱ-ㅎ|가-힣|a-z|A-Z|0-9|] : 한글, 소문자 영어, 대문자 영어, 숫자에 해당하는 문자 1개를 의미
+ : 문자 1개 이상을 의미
$ : 문자열의 끝을 의미

const regex = /^[ㄱ-ㅎ|가-힣|a-z|A-Z|0-9|]+$/;

let str = "aaa123";
console.log(regex.test(str));   //true

str = "aaAAbbB123"; 
console.log(regex.test(str));   //true

str = "aA가나다라B123ttt";
console.log(regex.test(str));   //true

str = "Hello1234";
console.log(regex.test(str));   //false

✔️ 위 코드를 실행하면, 영어가 포함된 Hello1234만 false를 리턴한다.


📌 2. 문자열에 한글만 있는지 확인

const regex = /^[ㄱ-ㅎ|가-힣]+$/;
const regex1 = /^[ㄱ-ㅎ|가-힣]/; 

let str = "aaa123";
console.log(regex.test(str));   //true

str = "aaAAbbB123"; 
console.log(regex.test(str));   //true

str = "aA가나다라B123ttt";
console.log(regex.test(str));   //true

str = "Hello1234";
console.log(regex.test(str));   //false

📌 3. 문자열에 알파벳만 있는지 확인

const regex = /^[a-z|A-Z]+$/;
const regex1 = /^[a-z|A-Z]/;  //regex1과 같이 써도 됨

let str = "abc";
console.log(regex.test(str));   //true

str = "aaAAbbB"; 
console.log(regex.test(str));   //true

str = "aA가나다라B123ttt";
console.log(regex.test(str));   //false

str = "Hello1234";
console.log(regex.test(str));   //false

📌 4. 문자열에 숫자만 있는지 확인

const regex = /^[0-9]+$/;
const regex1 = /^[0-9]/;

let str = "123";
console.log(regex.test(str));   //true

str = "aaAAbbB123"; 
console.log(regex.test(str));   //false

str = "Hello1234";
console.log(regex.test(str));   //false

📁 이처럼 문자열에 한글, 알파벳, 숫자만 있는지 확인하고 싶으면 '/^[조건입력]+$/.test(str)'나 '/^[조건입력] /.test(str)' 과 같은 형태로 입력해주면 된다.


🔔 내 문제
Input 입력창에 1자리 한글만 입력되어 있는지 확인해야 한다.

/[^가-힣]/.test(str)

^가 문자열의 시작을 의미하므로 []안에 ^를 넣어줘야 원하는 조건을 설정해줄 수 있었다.

0개의 댓글