3 min read
•Question 14 of 62easyHow to parse and format URLs in Node.js?
Working with URLs using the URL module.
What You'll Learn
- URL parsing
- URLSearchParams
- Building URLs
URL Class
code.jsJavaScript
const { URL, URLSearchParams } = require('url');
// Parse URL
const myURL = new URL('https://user:pass@example.com:8080/path?query=1#hash');
console.log(myURL.href); // Full URL
console.log(myURL.protocol); // 'https:'
console.log(myURL.username); // 'user'
console.log(myURL.password); // 'pass'
console.log(myURL.host); // 'example.com:8080'
console.log(myURL.hostname); // 'example.com'
console.log(myURL.port); // '8080'
console.log(myURL.pathname); // '/path'
console.log(myURL.search); // '?query=1'
console.log(myURL.hash); // '#hash'URLSearchParams
code.jsJavaScript
// Parse query string
const params = new URLSearchParams('name=John&age=30');
console.log(params.get('name')); // 'John'
console.log(params.has('age')); // true
// Iterate
for (const [key, value] of params) {
console.log(key, value);
}
// Modify
params.set('age', '31');
params.append('city', 'NYC');
params.delete('name');
console.log(params.toString()); // 'age=31&city=NYC'Building URLs
code.jsJavaScript
const url = new URL('https://api.example.com');
url.pathname = '/users';
url.searchParams.set('page', '1');
url.searchParams.set('limit', '10');
console.log(url.href);
// https://api.example.com/users?page=1&limit=10
// Relative URL
const relative = new URL('/api/data', 'https://example.com');
console.log(relative.href); // https://example.com/api/data