WEB/Javascript

[JS] 기본문법 - 문자열 -정규표현식

탱! 2022. 5. 13. 11:43

정규표현식을 사용하면 많은 코드를 줄일 수 있다.

예를 들어 정규표현식을 사용하지 않은 경우

const string1 = "Kim 010-1234-5678"

if (
    string1.includes("Kim")||
    string1.includes("010")||
    string1.includes("-")
){
    alert("Kim 의 전화번호는 "+ string1+ "입니다.")
}

각각의 문자열들이 변수안에 포함되어있는 가의 조건문을 필요한 만큼 사용해야한다.

만일 정규표현식을 사용한다면 한 줄에 끝난다.

const string1 = "Kim 010-1234-5678"

if (/010|-|Kim/.test(string1)) {
    alert("Kim 의 전화번호는 "+ string1+ "입니다.")
}

/이문자가/.test(여기에포함되어있는가?)

 

결과를 불리언값으로 출력한다.

/한/.test('한국은 여름이에요'); //true
/고/.test('한국은 여름이에요'); //false

/^what/.test('what was that?'); //true 시작문자가 'what'인가?
/^what/.test('where we are?'); //false

/\d/.test('My number is 04593');//true 숫자가 포함되어 있는가
/\d/.test('and i living in east dom');//false

/teaching.*/.test('teaching is creating to');//true 'teach'뒤에오는 문자가 0회 이상 있는가?
/teach.*/.test('teaching is creating to');//true 없어도 무조건 'teach'만 있다면 true

/여*오/.test('여름이 오고 있어요');//true '여'와 '오' 사이 다른 문자가 있는가?
/가*을/.test('가을이 좋아요');//true
/겨*울/.test('겨343울 왕국');//true

/\d+-/.test('010-1234-5678');//true '숫자-'형식이 있는가