Web APIs (Part 4) – parse url with URL, URLSearchParams

Tram Ho

Introduce

Today will be a fairly brief article: v

URL

Normally, to get the current url information, we usually use window.location and get the following result:

In addition to window.location , the URL also provides a number of properties, methods that can help us easily create, read and edit url components such as hostname , pathname , …

URLSearchParams

Parse query string is one of the common problems when working with urls. There are many excellent libraries that solve this problem such as qs or query-string with tens of millions of downloads every week.

However, to parse the simple urls, we can use the existing URLSearchParams :

We will first use window.location.search to get the query string of the current url. Assume the following result:

Now if we want to get place we will use the get method or getAll of URLSearchParams

So we have obtained the value of the query, which is quite simple.

We can also loop through searchParams to get all (key,value) searchParams.forEach (key,value) using for...of or searchParams.forEach

Browser compatibility

Conclude

The article only came here, hoping to help people in upcoming projects. Wished everyone success

Share the news now

Source : Viblo