Parsing URLs sounds simple until you actually try it. There are dozens of edge cases: URLs with no path, query parameters containing = in values, fragments that include ? , internationalized domain names. The URL API handles all of this correctly. Here's how to use it.
The URL API
URL is a browser-native class (also available in Node.js since v10) that parses a URL string into its component parts:
const url = new URL ( ' https://example.com:8080/path/page?q=hello+world&lang=en#section ' );
url . protocol // "https:" url . hostname // "example.com" url . port // "8080" url . host // "example.com:8080" url . pathname // "/path/page" url . search // "?q=hello+world&lang=en" url . hash // "#section" url . origin // "https://example.com:8080" url . href // full URL string
Enter fullscreen mode
Exit fullscreen mode
The parser handles edge cases automatically.…