How to create a URL object using JavaScript?

The URL object in JavaScript provides a convenient way to parse and manipulate URLs. It extracts components like protocol, host, pathname, and search parameters from URL strings.

Syntax

let url = new URL(urlString);
let url = new URL(urlString, baseURL);

Parameters

  • urlString - The URL string to parse
  • baseURL - (Optional) Base URL for relative URLs

Example

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>URL Object Example</title>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .result {
         font-size: 18px;
         font-weight: 500;
         color: rebeccapurple;
         margin: 20px 0;
      }
      .btn {
         padding: 10px 20px;
         background-color: #007bff;
         color: white;
         border: none;
         cursor: pointer;
         border-radius: 5px;
      }
   </style>
</head>
<body>
   <h1>URL Object in JavaScript</h1>
   <div class="result"></div>
   <button class="btn">Parse URL</button>
   <h3>Click the button to create and display URL object properties</h3>

   <script>
      let resEle = document.querySelector(".result");
      let url = new URL("https://www.example.com/path/page?name=john&age=25#section");
      
      document.querySelector(".btn").addEventListener("click", () => {
         resEle.innerHTML = "";
         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 += "Hash: " + url.hash + "<br>";
         resEle.innerHTML += "Origin: " + url.origin + "<br>";
      });
   </script>
</body>
</html>

Common URL Properties

Property Description Example Value
protocol URL scheme https:
host Hostname with port www.example.com
pathname Path portion /path/page
search Query string ?name=john&age=25
hash Fragment identifier #section

Working with Search Parameters

<script>
   let url = new URL("https://api.example.com/users?page=1&limit=10");
   let params = url.searchParams;
   
   console.log("Page:", params.get("page"));
   console.log("Limit:", params.get("limit"));
   
   // Add new parameter
   params.set("sort", "name");
   console.log("Updated URL:", url.toString());
</script>

Conclusion

The URL object simplifies URL parsing and manipulation in JavaScript. Use it to extract components or build URLs programmatically with proper encoding.

Updated on: 2026-03-15T23:18:59+05:30

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements