웹개발 중 현재 페이지에서 URL에 있는 param값을 가져오고 해당 값으로 js단에서 처리를 하고자 할 때 값을 가져오는 방법은 html dom api인 Location, URLSearchParams 를 사용하면 금방 구현 할 수 있다. 쉽게 url의 값을 가져올 수 있습니다.
How to use
const url = 'https://devpuer.tistory.com/view.do?detailsKey=1&focus=1';
// 전체 url https://devpuer.tistory.com/view.do?detailsKey=1&focus=1
console.log(location.href)
// url중 get 부분 ?detailsKey=1&focus=1
console.log(location.search)
// 도메인 빼고 뒤 경로 부분 /view.do
console.log(location.pathname)
// 도메인+포트번호 devpuer.tistory.com
console.log(location.host)
const urlParam = new URLSearchParams(location.search);
// url get 부분의 값을 가져옴 1
console.log(urlParam.get('focus'))
Location API
자주 쓰는 속성으로는 href, host, hathname, search가 있고 함수는 아래와 같다.
메서드 명 | 설명 |
assign(url) | 해당 url에서 리소스를 로드한다. |
reload() | 현재 url를 다시 로드한다. (새로고침) |
replace(url) | href로 url를 바꾼것과는 다르게 세션에 해당 페이지를 저장하지 않음 (뒤로가기 히스토리에 남지 않음) |
toString(url) | href를 출력할 때 사용 (href로도 가능) |
Location - Web APIs | MDN
The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location, accessible via Document.location and Windo
developer.mozilla.org
URLSearchParams
인터페이스인 URLSearchParams는 url의 쿼리 문자열과 함께 작동되는 유틸리티 메서드이다. 즉, url의 서치 부분을 넣어주면 미리 정의된 함수를 사용할 수 있다는 것이다.
그 함수는 아래와 같다.
속성 명 및 함수 명 | 설명 |
size | param의 갯수 키의 갯수가 출력 |
append({key: value}) | 키/값으로 param추가(생성) |
delete(key) | 키값으로 param 제거(삭제) |
entries() | param 값 반복 |
forEach() | 콜백 함수로 반복 가능 |
get(key) | 해당 key의 첫번째 값이 반환 |
See the Pen Untitled by 정재준 (@ihistdxo-the-builder) on CodePen.
URLSearchParams - Web APIs | MDN
The URLSearchParams interface defines utility methods to work with the query string of a URL.
developer.mozilla.org
'Dev > WEB' 카테고리의 다른 글
[SEO] 검색 사이트 노출(검색) 방지 및 수집 금지 요청 (0) | 2023.09.08 |
---|---|
[JS] scrollIntoView 해당 요소로 Focus하기, 해당 요소로 스크롤 하기 (0) | 2023.07.28 |
[Fullcalendar] 라이브러리 이용해서 달력 만들기, 사용법 정리 (0) | 2023.07.26 |
[http-server] HTML 테스트를 위한 웹 서버 띄우기 (빠르게) (0) | 2023.07.15 |
[CSS] Web font 적용 (with. Apple SD Gothic Neo) (0) | 2023.06.29 |