자바스크립트 정규표현식으로 문자열이 특정 패턴 만족하는지 확인하기

ino5·2022년 7월 4일

요약

/정규식/.test(문자열) 이용해서 해당 문자열이 특정 패턴을 만족하는지 확인할 수 있다.

참고로 문자열.match(/정규식/) 을 이용한 방법도 있다.

정규식 참고 링크

https://myeonguni.tistory.com/1555

글 좋은 것 같다..

📖 기본 예제

다음 모든 코드의 결과 true로 나온다.

문자열이 abc인지

<script>
    const regex = /^abc$/;
    const str = "abc";
    console.log(regex.test(str));
</script>

문자열이 숫자로만 이루어졌는지

<script>
    const regex = /^[0-9]+$/;
    const str = "123";
    console.log(regex.test(str));
</script>

문자열이 숫자로 시작해서 영어로 끝나는지

<script>
    const regex = /^[0-9]+[0-9a-zA-Z]*[a-zA-Z]+$/;
    const str = "12a33a";
    console.log(regex.test(str));
</script>

문자열이 한글로만 이루어졌는지

<script>
    const regex = /^[ㄱ-ㅎㅏ-ㅣ가-힣]+$/;
    const str = "가ㄱㅁㅋㅏㅜ";
    console.log(regex.test(str));
</script>

1로 시작하는 세자리 숫자인지

<script>
    const regex = /^1[0-9]{2}$/;
    const str = "123";
    console.log(regex.test(str));
</script>
profile
지금은 네이버 블로그만 해요... https://blog.naver.com/chero77

0개의 댓글