URL Parser Utility
Parse and manipulate URL components with query string support
Description
A utility class for parsing URLs, extracting components, and manipulating query parameters. Handles encoding/decoding automatically.
Features
- Parse URL components (protocol, host, path, query)
- Query parameter manipulation
- URL building from components
Code
class URLParser { constructor(url) { this.url = new URL(url); } getProtocol() { return this.url.protocol.slice(0, -1); } getHost() { return this.url.host; } getPath() { return this.url.pathname; } getQueryParam(key) { return this.url.searchParams.get(key); } setQueryParam(key, value) { this.url.searchParams.set(key, value); return this; } removeQueryParam(key) { this.url.searchParams.delete(key); return this; } getAllQueryParams() { const params = {}; this.url.searchParams.forEach((value, key) => { params[key] = value; }); return params; } toString() { return this.url.toString(); }}module.exports = URLParser;
const URLParser = require('./urlParser');const parser = new URLParser('https://example.com/path?foo=bar');console.log('Protocol:', parser.getProtocol());console.log('Host:', parser.getHost());console.log('Path:', parser.getPath());// Modify query paramsparser.setQueryParam('page', '1');console.log('Updated URL:', parser.toString());
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.