Preface
In a URL, query parameter string values usually provide information about the request, such as the search parameter or the ID of the object being used. If you process any business or request logic on the front end, it is important to know how to retrieve query string values from URLs. This article shares three ways to get parameters from URLs.
URLSearchParams
All major browser versions except IE 11 support thisURLSearchParams
Interface. It works by parsing the query string of the URL and providing a way to access the value.
For example:
One of the disadvantages of this interface is that you have to pass only the query string for the URL to it. This is easy to do if you are using the current browser URL, because you just need to go through. If you use any other URL, you need to parse and pass the query string separately.
const params = new URLSearchParams("q=devpoint&page=1"); ("q"); // 'devpoint' ("page"); // '1'
To parse query parameters into objects, useof
.entries()
method, this method returns aIterator
key/value
Yes, andIt is converted to an object.
const params = new URLSearchParams("q=devpoint&page=1"); const entries = (); (entries); // {q: 'devpoint', page: '1'}
URL
In addition to IE 11, all major browser versions are also supported.URL
API. It provides a more flexible way to parse URLs and also provides a way to access query string values.
For example:
const url = new URL("/search?q=devpoint&page=1"); const searchParams = ; ("q"); // 'devpoint' ("page"); // '1'
and
URLSearchParams
The returned instance object type is the same.
The aboveurl
The target will alsoURL
All parts of are broken down into individual parts.
For example:
; // '/search?q=devpoint&page=1' ; // '' ; // 'https:' ; // '' ; // '' ; // '' ; // '/search' ; // '?q=devpoint&page=2' ; // ''
Pure JS
If you cannot access the above API for some reason or want more control over parsing, you can use the following code to parse the query string to an object.
function getQueryParams(url) { const paramArr = (("?") + 1).split("&"); const params = {}; ((param) => { const [key, val] = ("="); params[key] = decodeURIComponent(val); }); return params; }
The effect after the function is executed is as follows:
getQueryParams("/search?q=devpoint&page=2"); // { q: 'devpoint', page: '2' }
This is the end of this article about JavaScript's three methods of obtaining URL parameter values. For more related content on obtaining URL parameter values by JS, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!