JavaScript URL basics

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

Use new URL(absoluteUrl) or new URL(path, base). Mutate properties to rebuild href.

JavaScript Syntax

JavaScript
const u = new URL("/docs", "https://example.com");
u.searchParams.set("page", "2");
console.log(u.href);
Try it Editor

How It Works

  1. Base + path. Resolves to an absolute URL.
  2. searchParams. Updates the query string.
  3. href. Full serialized URL.

Examples

Example 1 — Read parts

Common fields.

JavaScript
const u = new URL("https://user:[email protected]:8080/a?b=1#c");
console.log(u.protocol);
console.log(u.host);
console.log(u.hash);
Try it Editor

How It Works

  1. host includes port when non-default.

Frequently Asked Questions

Provide a base: new URL("/x", "https://example.com").
Yes—global URL in modern Node.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful