Url Parsing in TypeScript

Here’s the translation of the Go URL parsing example to TypeScript, formatted for Hugo:

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

import { URL } from 'url';

function main() {
    // 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.
    let u: URL;
    try {
        u = new URL(s);
    } catch (error) {
        console.error(error);
        return;
    }

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

    // URL class doesn't separate username and password,
    // so we need to parse them manually.
    const [username, password] = (u.username && u.password) 
        ? [u.username, u.password] 
        : [null, null];
    console.log(`${username}:${password}`);
    console.log(username);
    console.log(password);

    // The host contains both the hostname and the port,
    // if present. We can access them separately.
    console.log(u.host);
    console.log(u.hostname);
    console.log(u.port);

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

    // To get query params in a string of 'k=v' format,
    // use 'searchParams'. You can also parse query params
    // into a map.
    console.log(u.search.slice(1)); // Remove leading '?'
    console.log(u.searchParams);
    console.log(u.searchParams.get('k'));
}

main();

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

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

This TypeScript example uses the built-in URL class from the url module to parse and manipulate URLs. The URL class provides properties and methods to access different parts of a URL, similar to the Go url.URL struct.

Note that TypeScript’s URL class handles authentication information (username and password) slightly differently, so we needed to parse that manually. Additionally, the query parameters are stored in a URLSearchParams object, which provides methods to access and manipulate the parameters.

The overall structure and functionality of the program remain similar to the original Go version, demonstrating how to parse and extract various components of a URL in TypeScript.