惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
J
Java Code Geeks
G
Google Developers Blog
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
月光博客
月光博客
B
Blog
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
博客园_首页
人人都是产品经理
人人都是产品经理
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Jina AI
Jina AI
S
SegmentFault 最新的问题
H
Help Net Security
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Parse URLs in JavaScript: The URL API vs Manual Pa...
Snappy Tools · 2026-05-02 · via DEV Community

Parsing URLs sounds simple until you actually try it. There are dozens of edge cases: URLs with no path, query parameters containing = in values, fragments that include ?, internationalized domain names. The URL API handles all of this correctly. Here's how to use it.

The URL API

URL is a browser-native class (also available in Node.js since v10) that parses a URL string into its component parts:

const url = new URL('https://example.com:8080/path/page?q=hello+world&lang=en#section');

url.protocol  // "https:"
url.hostname  // "example.com"
url.port      // "8080"
url.host      // "example.com:8080"
url.pathname  // "/path/page"
url.search    // "?q=hello+world&lang=en"
url.hash      // "#section"
url.origin    // "https://example.com:8080"
url.href      // full URL string

Enter fullscreen mode Exit fullscreen mode

The parser handles edge cases automatically. Standard ports are omitted from host: http://example.com:80/ gives host === "example.com".

URLSearchParams: the right way to handle query strings

Don't split on & and = to parse query parameters — values can contain encoded & and = characters. Use URLSearchParams:

const url = new URL('https://example.com?q=hello+world&tags=js&tags=css');
const params = url.searchParams;

params.get('q')      // "hello world" — decodes + as space
params.getAll('tags') // ["js", "css"] — handles repeated params
params.has('tags')   // true

// Iterate all params
for (const [key, value] of params) {
  console.log(key, value);
}
// q hello world
// tags js
// tags css

Enter fullscreen mode Exit fullscreen mode

Building query strings

const params = new URLSearchParams({
  q: 'hello world',
  sort: 'date',
  page: '1'
});
params.toString()  // "q=hello+world&sort=date&page=1"

// Append without replacing
params.append('tags', 'javascript');
params.append('tags', 'css');
params.toString()  // "q=hello+world&sort=date&page=1&tags=javascript&tags=css"

Enter fullscreen mode Exit fullscreen mode

Modifying URL parameters

const url = new URL('https://example.com?page=1&sort=date');

url.searchParams.set('page', '2');  // update
url.searchParams.delete('sort');    // remove
url.searchParams.append('filter', 'active');  // add

url.href  // "https://example.com/?page=2&filter=active"

Enter fullscreen mode Exit fullscreen mode

Relative URL resolution

URL handles relative URLs when given a base:

new URL('/about', 'https://example.com')
  .href  // "https://example.com/about"

new URL('../images/photo.jpg', 'https://example.com/blog/post/')
  .href  // "https://example.com/blog/images/photo.jpg"

new URL('?page=2', 'https://example.com/articles')
  .href  // "https://example.com/articles?page=2"

Enter fullscreen mode Exit fullscreen mode

This is the correct way to resolve relative links when scraping or building link crawlers.

URL encoding and decoding

URL handles percent-encoding automatically:

const url = new URL('https://example.com/search');
url.searchParams.set('q', 'café & creme brûlée');
url.href  // "https://example.com/search?q=caf%C3%A9+%26+creme+br%C3%BBl%C3%A9e"

Enter fullscreen mode Exit fullscreen mode

For manual encoding/decoding:

// Encode a component value (e.g., query parameter value)
encodeURIComponent('hello world & more')  // "hello%20world%20%26%20more"

// Encode a full URL (preserves :, /, ?, =, &, #, @)
encodeURI('https://example.com/path?q=hello world')
// "https://example.com/path?q=hello%20world"

// Decode
decodeURIComponent('hello%20world')  // "hello world"

Enter fullscreen mode Exit fullscreen mode

Use the URL Encoder/Decoder to manually encode/decode URL components in the browser without writing code.

Validating URLs

function isValidUrl(string) {
  try {
    new URL(string);
    return true;
  } catch {
    return false;
  }
}

isValidUrl('https://example.com')  // true
isValidUrl('not a url')            // false
isValidUrl('//example.com')        // true — protocol-relative URL

Enter fullscreen mode Exit fullscreen mode

Note: //example.com is a valid protocol-relative URL. If you want to require a specific protocol:

function isHttpUrl(string) {
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
}

Enter fullscreen mode Exit fullscreen mode

Extracting the domain from a URL

new URL('https://sub.example.co.uk/path').hostname
// "sub.example.co.uk"

// hostname vs host:
new URL('https://example.com:443/path').host      // "example.com:443"
new URL('https://example.com:443/path').hostname  // "example.com"

Enter fullscreen mode Exit fullscreen mode

hostname strips the port. host includes it.

URL in Node.js

URL is globally available in Node.js since v10. For older compatibility, import it:

const { URL, URLSearchParams } = require('url');

Enter fullscreen mode Exit fullscreen mode

It's also available in Web Workers and Service Workers in the browser.

What about the legacy document.createElement('a') trick?

Before the URL API, developers used a DOM <a> element to parse URLs:

const a = document.createElement('a');
a.href = 'https://example.com/path';
a.hostname  // "example.com"

Enter fullscreen mode Exit fullscreen mode

This only works in the browser (not Node.js), can behave differently across browsers for edge cases, and doesn't support URLSearchParams. Use the URL API instead — it's available everywhere that matters and handles edge cases correctly.


The URL API is one of those Web APIs that, once you start using it, you wonder how you ever parsed URLs without it. URLSearchParams in particular eliminates an entire category of bugs from query string handling. If you're still splitting on ? and &, there's a better way.