查看原文
其他

【英】在JavaScript中使用查询参数

Antonio Santiago 前端早读课 2019-12-16

前言

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:

  1. if(window.URLSearchParams) {

  2. // Support :)

  3. }

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:

  1. constparams= newURLSearchParams('version=1&name=john&lastname=nieve')

  2. // or

  3. 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:

  1. 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:

  1. params.get('version') // 1

  2. params.get('name') // john

  3. params.get('name') // john


  4. params.set('lastname', 'stark')

  5. params.get('lastname') // stark


  6. params.has('lastname') // true

  7. params.has('age') // false

We can also add new parameters and work with array parameters:

  1. params.set('tags', 'bastard')

  2. params.append('tags', 'lord')


  3. params.get('tags') // bastard

  4. params.getAll('tags') // ['bastard', 'lord']

Note the difference between get and getAll when working with array parameters.

Or simply delete params:

  1. params.delete('lastname')

Finally we can convert the URLSearchParams back into a string with the:

  1. 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:

  1. const url = new URL('https://got-api.com?version=1&name=john&lastname=nieve');

  2. constparams= newURLSearchParams(url.search);


  3. params.toString() // version=1&name=john&lastname=nieve

关于本文 作者:@Antonio Santiago 原文:https://www.acuriousanimal.com/blog/2019/11/09/urlsearchparams/

为你推荐


【英】每天把你的待办事项控制在三件事上


【英】高级软件工程师职业生涯的下一步

    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存