자바스크립트

[javascript] URL 정규식

grin-quokka 2019. 8. 14. 21:32
  • URL의 구성 요소 (출처)

  • 해시뱅 #!

  • 정규식을 테스트 할 수 있는 사이트 (https://regex101.com/)

    • 시각화해서 결과를 보여주고, 정규식에 대한 설명도 자세히 있고, 완성된 정규식을 바로 쓸 수 있게 코드로도 만들어준다.

      • URL 주소 match를 위한 정규식 (https://tools.ietf.org/html/rfc3986#appendix-B)

        • 요소별로 그룹으로 묶인다. 해당하는 그룹이 없을 경우 undefined

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          const url = 'http://github.com/p/a/t/h?query=string';
          const regex = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/g;
          const matches = regex.exec(url)
          matches.forEach(cur => {
            console.log(cur)
          });
           
          /* 결과
          'http://github.com/p/a/t/h?query=string'
          'http:'
          'http'
          '//github.com'
          'github.com'
          '/p/a/t/h'
          '?query=string'
          'query=string'
          undefined
          undefined
          */
           
          cs