const pattern = /^[a-zA-Z0-9\uAC00-\uD7A3\s]*$/
  • ^ : 문자열 시작
  • \uAC00-\uD7A3 : 한글문자 ( 가 부터 힣 까지)
  • \s  : 공백 문자 ( 스페이스, 탭..)
  • * : 한번 이상 반복 가능
  • $ : 문자열의 끝

모든 공백제거

let str = "h e l l o w o r l d"
str = str.replace(/\s+/g, '');// helloworld

 

앞뒤 공백 제거

let str = "   hello   ";
str = str.trim(); // "hello"

 

공백확인

const str = " 123 4 "
/\s/.test(str) // true

\s 는 모든 유형의 공백 문자를 나타내는 메타 문자

 

이 메일 정규 표현식

const emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
emailRegex.test(testEmailAddress); // true || false

 

  • ^[a-z0-9._%+-]+: 이메일의 로컬 파트에서 영어 소문자 알파벳, 숫자, 점(.), 밑줄(_), 퍼센트(%), 플러스(+), 하이픈(-)을 허용
  • @[a-z0-9.-]+: 도메인 부분에서 영어 소문자 알파벳, 숫자, 점(.), 하이픈(-)을 허용
  • \.[a-zA-Z]{2,}$: 최상위 도메인 부분에서 최소 2자 이상의 영어 알파벳을 허용

 

이메일의 시작과 끝에 특수문자 있는지 확인

 

const specialChars = /[!#$%&'*+/=?^_`{|}~-]/;
const localPart = email.split('@')[0];

if (specialChars.test(localPart[0]) || specialChars.test(localPart[localPart.length - 1])) {
  return false;
}

 

특수문자가 연속으로 사용되었는지 확인

for (let i = 0; i < localPart.length - 1; i++) {
  if (specialChars.test(localPart[i]) && specialChars.test(localPart[i + 1])) {
    args.constraints[0] = 'consecutiveSpecialChars';
    return false;
  }
}

숫자만 추출

const str = "aAb1B2cC34oOp";
const numbers = str.match(/\d+/g);
// ["1", "2", "34"]

/\d+/g

  • \d+ : 연속된 하나이상의 숫자에 매칭
  • g : 전체 문장
  • 전체 문장에서 연속된 하나이상의 숫자에 매칭되는 문자를 찾는다. 

참고로 \D+ 는 숫자가 아닌 문자들을 찾는 패턴

 

3x , 7, 2x 추출

const str = "3x + 7 + 2x"
const numberX = str.match(/\b\d+x\b/g); // [ '3x', '2x'] 
const number = str.match(/\b\d+\b/g);   // ['7']
const number2 =str.match(/\d+/g);       //['3', '7', '2']

/\b\d+\b/g

  • \b : 단어의 경계를 의미 --- |on| |the| |board|  에서 | 가 경계
  • \d+x : 연속된 하나이상의 숫자와 x로 이루어진 패턴
  • g : 전체 문장

+ Recent posts