【英】在JavaScript中使用查询参数
前言
URLSearchParams可以了解一下。本期英文由@Antonio Santiago分享。
英文从这开始~~
No matter if you work with JavaScript at client or server side, at some point you'll need to work with urls and its query params.
As example, I'm currently using react-router in my project, which is an great tool. I can define dynamic routes with path params and easily react-router returns me these params within the match variable and the rest of url information in the location variable, but how can I easily access to query params?
There are great libraries for this purpose -like query-string or qs- but the question is: why increase in some more bytes the size of your package when there is a native solution? 😄 The URLSearchParams.
Detect feature support
As all native implementation remember the support depends on the browser version. See compatibilities here. We can check it with:
if(window.URLSearchParams) {
// Support :)
}
Construct an instance
The most typical usage is to build an URLSearchParams instance from a query string. Note it is also valid to pass a string that start with ?, the URLSearchParams will strip it out:
constparams= newURLSearchParams('version=1&name=john&lastname=nieve')
// or
constparams= newURLSearchParams('?version=1&name=john&lastname=nieve')
🤓 Be aware to not pass string url! Or it will be interpreted as the parameter name. For example, given:
constparams= newURLSearchParams('https://some_api.com?paramA=valueA')
You'll get the three parameters named: https://some_api.com?paramA with value valueA.
Working with params
Once we have an instance it is easy to get or set the parameters values:
params.get('version') // 1
params.get('name') // john
params.get('name') // john
params.set('lastname', 'stark')
params.get('lastname') // stark
params.has('lastname') // true
params.has('age') // false
We can also add new parameters and work with array parameters:
params.set('tags', 'bastard')
params.append('tags', 'lord')
params.get('tags') // bastard
params.getAll('tags') // ['bastard', 'lord']
Note the difference between get and getAll when working with array parameters.
Or simply delete params:
params.delete('lastname')
Finally we can convert the URLSearchParams back into a string with the:
params.toString() // version=1&name=john&tags=bastard&tags=lord
Working with URLs
If we have an URL string the easy way to get the params is using the URL object:
const url = new URL('https://got-api.com?version=1&name=john&lastname=nieve');
constparams= newURLSearchParams(url.search);
params.toString() // version=1&name=john&lastname=nieve
关于本文 作者:@Antonio Santiago 原文:https://www.acuriousanimal.com/blog/2019/11/09/urlsearchparams/
为你推荐