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
, …
1 2 | url <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">URL</span> <span class="token punctuation">(</span> <span class="token string">'https://developer.mozilla.org/en-US/docs/Web/API/URL#top'</span> <span class="token punctuation">)</span> |
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:
1 2 | <span class="token keyword">var</span> paramsString <span class="token operator">=</span> <span class="token string">"?user=trieu-quan-su&place=quan-net&place=rung"</span> <span class="token punctuation">;</span> |
Now if we want to get place
we will use the get
method or getAll
of URLSearchParams
1 2 3 4 | <span class="token keyword">var</span> searchParams <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">URLSearchParams</span> <span class="token punctuation">(</span> paramsString <span class="token punctuation">)</span> <span class="token punctuation">;</span> searchParams <span class="token punctuation">.</span> <span class="token keyword">get</span> <span class="token punctuation">(</span> <span class="token string">'place'</span> <span class="token punctuation">)</span> <span class="token comment">// quan-net</span> searchParams <span class="token punctuation">.</span> <span class="token function">getAll</span> <span class="token punctuation">(</span> <span class="token string">'place'</span> <span class="token punctuation">)</span> <span class="token comment">// ["quan-net", "rung"]</span> |
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