Menu

1 / 2

How to Parse URLs in JavaScript: The URL API vs Manual Parsing

DEV Community·Snappy Tools·6 months ago
#RzN31DnT
#section#url#javascript#webdev#example
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.