URL Parsing and Manipulation
Parse and build URLs in Node.js. Handle query parameters easily.
URL Parsing
Parse and manipulate URLs with the URL class.
Parsing URLs
```javascript const myURL = new URL('https://example.com:8080/path?name=john&age=30#section');
console.log(myURL.protocol); console.log(myURL.hostname); console.log(myURL.port); console.log(myURL.pathname); console.log(myURL.search); console.log(myURL.hash); ```
**Output:** ``` https: example.com 8080 /path ?name=john&age=30 #section ```
Query Parameters
```javascript const url = new URL('https://api.example.com/users?role=admin&status=active');
console.log(url.searchParams.get('role')); console.log(url.searchParams.get('status'));
url.searchParams.append('limit', '10');
url.searchParams.set('role', 'user');
url.searchParams.delete('status');
console.log(url.toString()); ```
**Output:** ``` admin active https://api.example.com/users?role=user&limit=10 ```
Building URLs
```javascript const apiURL = new URL('/api/users', 'https://example.com'); apiURL.searchParams.set('page', '1'); apiURL.searchParams.set('limit', '20');
console.log(apiURL.toString()); ```
**Output:** `https://example.com/api/users?page=1&limit=20`
Real Example: API Client
```javascript function fetchUsers(filters) { const url = new URL('https://api.example.com/users'); if (filters.role) { url.searchParams.set('role', filters.role); } if (filters.page) { url.searchParams.set('page', filters.page); } if (filters.limit) { url.searchParams.set('limit', filters.limit); } return fetch(url.toString()); }
fetchUsers({ role: 'admin', page: 2, limit: 50 }); ```
Real Example: Express Routes
```javascript const express = require('express'); const app = express();
app.get('/search', (req, res) => { const query = req.query.q; const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; const nextURL = new URL(req.originalUrl, `http://${req.headers.host}`); nextURL.searchParams.set('page', page + 1); res.json({ results: [], nextPage: nextURL.toString() }); });
app.listen(3000); ```
URLSearchParams Standalone
```javascript const params = new URLSearchParams(); params.append('name', 'John Doe'); params.append('email', 'john@example.com');
console.log(params.toString());
for (const [key, value] of params) { console.log(`${key}: ${value}`); } ```
**Output:** ``` name=John+Doe&email=john%40example.com name: John Doe email: john@example.com ```
Key Takeaway
URL class makes parsing easy. Use `searchParams` for query strings. Build URLs programmatically. Automatically handles encoding.