Skip to main content
0 reactions

How to Build a Full URL from a Path with new URL() in JavaScript

A card titled new URL() in JavaScript, labelled JavaScript Basics, showing the path /contact on the base address example.com/shop/books giving example.com/contact.
new URL() in JavaScript: Turn a path into a full web address.

The URL constructor builds a web address. Give it a path and a base address, and it puts the path onto the base’s site: new URL("/contact", "https://example.com/shop/books") gives https://example.com/contact. URL is built into browsers and Node.js.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
new URL(path, base)
  • new URL: creates a URL object.
  • path: the address to work out, such as /contact.
  • base: a full address. It’s used when path isn’t a full address itself.

See URL() constructor (opens in a new tab) on MDN.

Prerequisites

The Example

A link to a shop’s contact page, built from the path /contact and the address of the page the visitor is on. The file is links.js.

Step 1: Write the Code

links.jsJavaScript
const page = new URL("/contact", "https://example.com/shop/books");

console.log(page.href);
console.log(page.pathname);

page.href is the whole address, and page.pathname is just its path.

Step 2: Run It

TerminalBash
node links.js
OutputPlain text
https://example.com/contact
/contact

The path starts with /, so it replaced the base’s path, /shop/books, and kept its site, https://example.com.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out the slash: new URL("contact", base)The path is put next to the base’s last part: https://example.com/shop/contactStart the path with / when it should start at the site’s root
Leaving out the base for a pathTypeError: Invalid URLPass a full address as the second argument

FAQ

What if the first argument is already a full address?

Then the base is ignored: new URL("https://other.example.org/x", base) gives https://other.example.org/x.

Conclusion

new URL(path, base) turns a path into a full address on the base’s site. Start the path with / to replace the whole path.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments