본문 바로가기

Frontend/JavaScript

자주쓰는 정규식 표현 (Regex) 정리

728x90
반응형
// Regex.js
// Chimsil 제작

// ID 체크
const idRegex = new RegExp(/^[a-z0-9_]{6,20}$/);

// 한글+영문 2글자 이상 20글자 이하 체크
const nameRegex = new RegExp(/^[가-힣]{1,6}$/);

// 성 regex 체크
const lastNameRegex = new RegExp(/^[가-힣]{1,3}$/);

//email형식 체크
const emailRegex = new RegExp(/(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/);

// 비밀번호 영어소문자+숫자+글자수(6글자 이상, 20글자 이하) 체크
const passwordRegex = new RegExp(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\w\W]{8,20}$/);

// 비밀번호 일치 확인
const passwordConfirmRegex = (password, passwordConfirm) => {
    return password === passwordConfirm;
};

// 휴대폰번호 형식 체크
const phoneRegex = new RegExp(/^\d{3}-\d{3,4}-\d{4}$/);

// 숫자만 입력받기
const numberRegex = (value) => {
  return value.replace(/[^0-9]/g, '');
};

// 휴대폰번호 하이폰(-) 정규식
const phoneHyphenRegex = (phone) => {
  return phone && phone?.replace(/[^0-9]/g, '')
  ?.replace(/^(\d{0,3})(\d{0,4})(\d{0,4})$/g, "$1-$2-$3")
  ?.replace(/(\-{1,2})$/g, "");
};

// 숫자 1000단위 콤마 찍기 함수
const numberWithCommas = (value) => {
  return value
    	.toString()
      .replace(/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g, (digit, fract) => fract || digit + ',');
};

// 사업자 등록 번호 하이폰(-) 정규식
const businessNumberHyphenRegex = (businessNumber) => {
  return businessNumber && businessNumber?.replace(/[^0-9]/g, '')
  ?.replace(/^(\d{0,3})(\d{0,2})(\d{0,5})$/g, "$1-$2-$3")
  ?.replace(/(\-{1,2})$/g, "");
};



export { 
  idRegex, 
  nameRegex, 
  lastNameRegex,
  emailRegex, 
  passwordRegex, 
  numberRegex,
  phoneRegex, 
  phoneHyphenRegex,
  passwordConfirmRegex,
  numberWithCommas,
  businessNumberHyphenRegex,
};
728x90
반응형