惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Parse URL in JavaScript: hostname, pathname, query, hash
Dmitri Pavlutin · 2020-07-07 · via Dmitri Pavlutin Blog

A Uniform Resource Locator, abbreviated URL, is a reference to a web resource (web page, image, file). The URL specifies the resource location and a mechanism to retrieve the resource (http, ftp, mailto).

For example, here's the URL of this blog post:


https://dmitripavlutin.com/parse-url-javascript


Often you need to access specific components of an URL: the hostname (e.g. dmitripavlutin.com), or pathname (e.g. /parse-url-javascript).

A convenient parser to access components of an URL is the URL() constructor.

In this post, I'm going to show you the structure of an URL and its main components. Then, I'm going to describe how to use the URL() constructor to easily pick components of an URL like hostname, pathname, query, or hash.

Table of Contents

  • 1. URL structure
  • 2. URL() constructor
  • 3. Query string
    • 3.1 Parsing the query string
  • 4. hostname
  • 5. pathname
  • 6. hash
  • 7. URL validation
  • 8. URL manipulation
  • 9. Summary

1. URL structure

An image worth a thousand words. Without much textual description, in the following image you can find the main components of an URL:

URL() constructor components in JavaScript

2. URL() constructor

The URL() is a constructor function to parse components of an URL:


const url = new URL(relativeOrAbsolute [, absoluteBase]);


relativeOrAbsolute argument can be either an absolute or relative URL. If the first argument is relative, then the second argument absoluteBase is obligatory and must be an absolute URL being the base for the relative path.

For example, let's initialize URL() with an absolute URL:


const url = new URL('http://example.com/path/index.html');

console.log(url.href); // => 'http://example.com/path/index.html'


Open the demo.

or combine relative and absolute URLs:


const url = new URL('/path/index.html', 'http://example.com');

console.log(url.href); // => 'http://example.com/path/index.html'


Open the demo.

The href property of the URL() instance returns the entire URL string.

After creating an URL() instance, you can access any URL component presented in the previous picture. For reference, here's the URL() instance interface:


interface URL {

href: USVString;

protocol: USVString;

username: USVString;

password: USVString;

host: USVString;

hostname: USVString;

port: USVString;

pathname: USVString;

search: USVString;

hash: USVString;

readonly origin: USVString;

readonly searchParams: URLSearchParams;

toJSON(): USVString;

}


where USVString type maps to a string when returned in JavaScript.

3. Query string

url.search property accesses the query string of the URL (the one that starts with ?):


const url = new URL(

'http://example.com/path/index.html?message=hello&who=world'

);

console.log(url.search); // => '?message=hello&who=world'


Open the demo.

If the query string is missing, url.search evaluates to an empty string '':


const url1 = new URL('http://example.com/path/index.html');

const url2 = new URL('http://example.com/path/index.html?');

console.log(url1.search); // => ''

console.log(url2.search); // => ''


Open the demo.

3.1 Parsing the query string

But more often you might need to access a specific query parameter.

An easy way to pick query parameters gives url.searchParams property. This property holds an instance of URLSearchParams.

URLSearchParams object provides lots of methods (like get(param), has(param)) to access the query string parameters.

Let's look at an example:


const url = new URL(

'http://example.com/path/index.html?message=hello&who=world'

);

console.log(url.searchParams.get('message')); // => 'hello'

console.log(url.searchParams.get('missing')); // => null


Open the demo.

url.searchParams.get('message') returns the value of message query parameter — 'hello'.

But accessing a non-existing parameter url.searchParams.get('missing') evaluates to null.

4. hostname

url.hostname property holds the hostname of the URL:


const url = new URL('http://example.com/path/index.html');

console.log(url.hostname); // => 'example.com'


Open the demo.

5. pathname

url.pathname property accesses the pathname of the URL:


const url = new URL('http://example.com/path/index.html?param=value');

console.log(url.pathname); // => '/path/index.html'


Open the demo.

If the URL doesn't have a path, the url.pathname property returns a slash character /:


const url = new URL('http://example.com/');

console.log(url.pathname); // => '/'


Open the demo.

6. hash

Finally, the hash is accessed using url.hash property:


const url = new URL('http://example.com/path/index.html#top');

console.log(url.hash); // => '#top'


Open the demo.

When the hash in the URL is missing, url.hash evaluates to an empty string '':


const url = new URL('http://example.com/path/index.html');

console.log(url.hash); // => ''


Open the demo.

7. URL validation

When new URL() constructor creates an instance, as a side effect, it also validates the URL for correctness. A TypeError is thrown if the URL value is invalid.

For example, http**://example.com is an invalid URL because of the ** characters after http.

Let's use this invalid URL to initialize the parser:


try {

const url = new URL('http**://example.com');

} catch (error) {

console.log(error); // => TypeError, "Failed to construct URL: Invalid URL"

}


Open the demo.

Because 'http**://example.com' is an invalid URL, as expected, new URL('http**://example.com') throws a TypeError.

8. URL manipulation

Aside from accessing URL components, the properties like search, hostname, pathname, hash are writeable — thus you can manipulate the URL.

For example, let's modify the hostname of an existing URL from red.com to blue.io:


const url = new URL('http://red.com/path/index.html');

console.log(url.href); // => 'http://red.com/path/index.html'

url.hostname = 'blue.io';

console.log(url.href); // => 'http://blue.io/path/index.html'


Open the demo.

Only origin and searchParams properties of the URL() instance are readonly. The other ones are writable and modify the URL when you change them.

9. Summary

The URL() constructor is handy for parsing (and validating) URLs in JavaScript.

new URL(relativeOrAbsolute [, absoluteBase]) accepts as the first argument an absolute or relative URL. When the first argument is relative, you have to indicate the second argument as an absolute URL that serves as the base for the first argument.

After creating the URL() instance, you can easily access the most common URL components like:

  • url.search for raw query string
  • url.searchParams for an instance of URLSearchParams to pick query string parameters
  • url.hostname to access the hostname
  • url.pathname to read the pathname
  • url.hash to determine the hash value

In terms of browser support, URL constructor is available in modern browsers. However, it is not available in Internet Explorer.

What is your favorite tool to parse URLs in JavaScript?