new URL Object

agnusdei·2023년 7월 20일
0

URL 객체를 생성하면 URL 문자열을 구조화된 방식으로 쉽게 분석하고 조작할 수 있게 됩니다. JavaScript의 URL 클래스를 사용하면 각 비트(프로토콜, 경로, 쿼리 문자열 등)를 따로 가져오거나 수정된 URL을 생성하는 데 도움이 됩니다.

주요 특징:
1. 속성을 통해 URL의 다양한 구성 요소에 직접 접근할 수 있습니다.

  • URL 전체 (href)
  • 프로토콜 (protocol)
  • 호스트 이름 및 포트 (host)
  • 호스트 이름 (hostname)
  • 포트 (port)
  • 경로 (pathname)
  • 쿼리 문자열 (search)
  • URL 해시 (hash)

예를 들어:

const url = new URL("https://example.com:8080/path1/path2?q=search#fragment");

console.log(url.href); // 'https://example.com:8080/path1/path2?q=search#fragment'
console.log(url.protocol); // 'https:'
console.log(url.host); // 'example.com:8080'
console.log(url.hostname); // 'example.com'
console.log(url.port); // '8080'
console.log(url.pathname); // '/path1/path2'
console.log(url.search); // '?q=search'
console.log(url.hash); // '#fragment'
  1. URL을 여러 가지 방식으로 수정할 수 있습니다:
const url = new URL("https://example.com/path1/path2");

url.protocol = 'http:';
url.host = 'new-domain.org';
url.pathname = '/new/path';
url.search = '?new-query=yes';
url.hash = '#new-fragment';

console.log(url.href); // 'http://new-domain.org/new/path?new-query=yes#new-fragment'
  1. 검색 매개 변수 인터페이스를 사용하여 쿼리 문자열을 쉽게 관리할 수 있습니다:
const url = new URL("https://example.com/path?q=old-search");

url.searchParams.set("q", "new-search");
console.log(url.href); // 'https://example.com/path?q=new-search'

url.searchParams.append("additional-param", "value");
console.log(url.href); // 'https://example.com/path?q=new-search&additional-param=value'

URL 객체를 사용하면 코드가 더 명확해지고 URL을 처리하는 방법이 더 간결해집니다. 이를 통해 실수를 줄이고 URL의 주요 요소에 직접 접근하는 데 도움이 됩니다.

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

정말 잘 읽었습니다, 고맙습니다!

답글 달기
Powered by GraphCDN, the GraphQL CDN