Url Parsing in JavaScript

Here’s the translation of the Go URL parsing example to JavaScript, formatted in Markdown suitable for Hugo:

Our URL parsing program demonstrates how to parse and extract various components from a URL string. Here’s the full source code:

const url = require('url');

// We'll parse this example URL, which includes a
// scheme, authentication info, host, port, path,
// query params, and query fragment.
const s = "postgres://user:pass@host.com:5432/path?k=v#f";

// Parse the URL and ensure there are no errors.
const u = new URL(s);

// Accessing the scheme is straightforward.
console.log(u.protocol.slice(0, -1));

// The 'username' and 'password' properties contain the authentication info.
console.log(`${u.username}:${u.password}`);
console.log(u.username);
console.log(u.password);

// The 'host' property contains both the hostname and the port,
// if present. Use 'hostname' and 'port' to extract them separately.
console.log(u.host);
console.log(u.hostname);
console.log(u.port);

// Here we extract the 'pathname' and the fragment after the '#'.
console.log(u.pathname);
console.log(u.hash.slice(1));

// To get query params in a string of 'k=v' format,
// use 'search'. You can also parse query params
// into a map using URLSearchParams.
console.log(u.search.slice(1));
const m = new URLSearchParams(u.search);
console.log(Object.fromEntries(m));
console.log(m.get('k'));

Running our URL parsing program shows all the different pieces that we extracted:

$ node url-parsing.js
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
{ k: 'v' }
v

This example demonstrates how to use the built-in url module and URL class in JavaScript to parse and extract information from URLs. The URL class provides properties for accessing different components of the URL, making it easy to work with complex URLs in your JavaScript applications.

The URLSearchParams class is used to parse and manipulate the query string of the URL. It provides methods to get, set, and delete query parameters, which is particularly useful when working with APIs or constructing URLs dynamically.

Remember that when working with URLs in a browser environment, you might need to handle relative URLs differently, and you may want to use the window.location object for accessing the current page’s URL components.