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
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 whenpathisn’t a full address itself.
See URL() constructor (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
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
node links.js
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
| Mistake | What happens | Do 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/contact | Start the path with / when it should start at the site’s root |
| Leaving out the base for a path | TypeError: Invalid URL | Pass 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
- URL() constructor (opens in a new tab) and URL (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments