url 객체
- window 내장함수인 url 객체는 URL을 만들고 파싱할 수 있게 해준다. URL객체를 반드시 활용해서 url을 만들 필요는 없지만 유용하게 사용할 수 있다.
URL 만들기
1
new URL(url, [base]);
-
url : 전체 URL 또는 path
-
base : 옵션. url에 path만 들어가면 base에 관련된 url로 생성된다.
- 전체 url을 넣었을 때
1 2 3 4 5
let url1 = new URL("https://javascript.info/profile/admin"); let url2 = new URL("/profile/admin", "https://javascript.info"); alert(url1); // https://javascript.info/profile/admin alert(url2); // https://javascript.info/profile/admin
- path만 넣었을 때
1 2 3 4
let url = new URL("https://javascript.info/profile/admin"); let newUrl = new URL("tester", url); alert(newUrl); // https://javascript.info/profile/tester
-
url객체를 통해서 이런 컴포넌트들에 접근할 수 있다.
1
2
3
4
5
let url = new URL("https://javascript.info/url");
alert(url.protocol); // https:
alert(url.host); // javascript.info
alert(url.pathname); // /url
SearchParams
url.searchParams에는 ?뒷부분의 파라미터가 온다. 이를테면
1
new URL("https://google.com/search?query=JavaScript");
에서는 query=JavaScript인 셈.
메소드들
append(name, value)– add the parameter by name,delete(name)– remove the parameter by name,get(name)– get the parameter by name,getAll(name)– get all parameters with the same name (that’s possible, e.g. ?user=John&user=Pete),has(name)– check for the existence of the parameter by name,set(name, value)– set/replace the parameter,-
sort()– sort parameters by name, rarely needed,- 예를 들면,
get(query)하면Javascript라는 값이 나오는 것이다
- 예를 들면,