typescriptbeginner

URL and Query String Parsing

Parse, construct, and manipulate URLs and query strings using the Node.js URL and URLSearchParams API.

typescript
// URL parsing (WHATWG URL API)
const url = new URL('https://example.com:8080/api/users?page=2&limit=10&sort=name#section');

console.log('Protocol:', url.protocol);   // https:
console.log('Host:', url.host);           // example.com:8080
console.log('Hostname:', url.hostname);    // example.com
console.log('Port:', url.port);           // 8080
console.log('Pathname:', url.pathname);   // /api/users
console.log('Search:', url.search);       // ?page=2&limit=10&sort=name
console.log('Hash:', url.hash);           // #section
console.log('Origin:', url.origin);       // https://example.com:8080

// Query parameters
const params = url.searchParams;
console.log('\npage:', params.get('page'));        // 2
console.log('limit:', params.get('limit'));        // 10
console.log('missing:', params.get('missing'));    // null
console.log('has sort:', params.has('sort'));       // true

// Iterate parameters
console.log('\nAll params:');
for (const [key, value] of params) {
  console.log(`  ${key} = ${value}`);
}

// Build URL with params
const apiUrl = new URL('https://api.example.com/search');
apiUrl.searchParams.set('q', 'nodejs tutorial');
apiUrl.searchParams.set('page', '1');
apiUrl.searchParams.append('tag', 'javascript');
apiUrl.searchParams.append('tag', 'nodejs');
console.log('\nBuilt URL:', apiUrl.toString());

// URLSearchParams from object
const qs = new URLSearchParams({
  name: 'Alice',
  age: '30',
  city: 'New York',
});
console.log('\nQuery string:', qs.toString());
// name=Alice&age=30&city=New+York

// Parse query string
const parsed = new URLSearchParams('foo=1&bar=2&baz=hello+world');
console.log('\nParsed: foo =', parsed.get('foo'));
console.log('Parsed: baz =', parsed.get('baz'));

// Modify params
params.set('page', '3');
params.delete('sort');
params.append('filter', 'active');
console.log('\nModified:', url.toString());

// Resolve relative URLs
const base = new URL('https://example.com/api/v1/');
const endpoint = new URL('users/42', base);
console.log('\nResolved:', endpoint.toString());

// Encode/decode URI components
const unsafe = 'hello world & foo=bar';
console.log('\nEncoded:', encodeURIComponent(unsafe));
console.log('Decoded:', decodeURIComponent(encodeURIComponent(unsafe)));

Use Cases

  • API URL construction
  • Query string parsing from requests
  • URL manipulation and normalization

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.