The composition of common urls is shown below:

Sources (The URL object)

Of course urls can also contain username and password fields, but most of them are in the standard and I haven’t seen them used in this way.

1. Standard apis (URLS and URLSearchParams)

The URL constructor creates an object that constructs a URL as follows:

const url = new URL(url, [base]) Resolve (url, base); resolve(url, base); resolve(url, base);
Copy the code

Here’s a concrete example:You can see the powerful url function, easy to use, the only problem is IE support is not very good, specific can seeThe URL on the MDN

There’s a searchParams property in there, which is kind of interesting, and it makes it very easy to get the key/value in the query, and that property isURLSearchParamsFor example:URLSearchParams is mainly used to process query parameters, the main problem is still not compatible with IE, other good, can also be used in web-worker

2. Use the A label

If it is a standard part of retrieving a URL, you can construct an A tag and the browser will automatically parse the attributes:

function parseUrl(url) {
  const el = document.createElement('a')
  el.href = url
  return el
}
Copy the code

Essentially building an HTML element, the A tag inherits the HTMLAnchorElement that contains the parsing of the url’s standard properties. If you need to implement URLSearchParams functionality, you can only use JS parsing, providing a simple handler function:

function parseQuery() {
  const search = location.search.slice(1)
  const pairs = search ? search.split('&') : []
  const query = {}
  for (let i = 0; i < pairs.length; ++i) {
    const [key, value] = pairs[i].split('=')
    query[key] = query[key] || decodeURIComponent(value)
  }
  return query
}
Copy the code

conclusion

Provide two common ways to parse urls. If you can avoid compatibility with IE, use standard urls and URLSearchParams. Otherwise, use open source libraries, or use the second solution described above.