Constructor new URL(urlString, base) parse URL thành các thành phần: protocol, host, hostname, port, pathname, search, hash. Rất hữu ích để thao tác query string an toàn.
Ví dụ
Parse URL https://google.com/image=23&size=440px:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>URL Object JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
</style>
</head>
<body>
<h1>Tạo và phân tích đối tượng URL</h1>
<div class="result"></div>
<button class="Btn">PHÂN TÍCH URL</button>
<h3>Nhấn nút để xem các thành phần của URL</h3>
<script>
const resEle = document.querySelector(".result");
const url = new URL("https://google.com/image=23&size=440px");
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = `protocol: ${url.protocol}<br>`;
resEle.innerHTML += `host: ${url.host}<br>`;
resEle.innerHTML += `pathname: ${url.pathname}<br>`;
resEle.innerHTML += `search: ${url.search}<br>`;
resEle.innerHTML += `searchParams.get('size'): ${url.searchParams.get('size')}<br>`;
});
</script>
</body>
</html>
Kết quả
Hiển thị: protocol: https:, host: google.com, pathname: /, search: ?image=23&size=440px, và lấy được tham số size=440px qua searchParams.
Mẹo: Dùng url.searchParams.append/set/delete để thao tác query string dễ dàng.