preface

As a front-end development, we often need to operate and process the URL, the most common one is to get the parameter value carried in the URL link. Those of you who use frameworks may find this easy, because frameworks provide many ways to easily retrieve the parameters carried by the URL link. But sometimes we can’t rely on the framework, we need to use native JS to get parameters, this is often encountered in the interview. Today we will rip the code by hand, using native JS to get URL link parameter values.

1. Summary of acquisition methods

There are several methods to obtain URL link parameters using native JS. Today we will explain the common ones in turn:

  1. By means of regular matching
  2. Utilize the A tag built-in method
  3. Use the split method to split the method
  4. Use the URLSearchParams method

2. Specific implementation methods

2.1 Regular matching method

This is a very moderate approach, but the point is that we need to know regular expressions.

The code is as follows:

<script> // use the regular expression let url = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100" // // to return the argument object function queryURLParams(url) { let pattern = /(\w+)=(\w+)/ig; // Define the regular expression let parames = {}; / / define the parameters object url. Replace (pattern, ($, $1, $2) = > {parames [$1] = $2; }); return parames; } console.log(queryURLParams(url)) </script>Copy the code

The previous code focuses on the definition of regular expression and the use of replace method, where,,, 1, $2 represent name=elephant, name, elephant, and so on. Replace and re can be used in more detail by yourself.

Effect:

2.2 Use the A label

This method is less used, because after all, there is a bit of black technology meaning in it. Its principle is to use the A tag to get some built-in attributes, such as href, hash, search and other attributes.

The code is as follows:

<script> let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100#smallpig" function queryURLParams(url) { / / 1. Let link = document.createElement('a'); link.href = url; let searchUrl = link.search.substr(1); Let hashUrl = link.hash.substr(1); Let obj = {}; 2. Store the hashUrl in the object. obj['HASH'] = hashUrl : null; Let list = searchurl.split ("&"); for (let i = 0; i < list.length; i++) { let arr = list[i].split("="); obj[arr[0]] = arr[1]; } return obj; } console.log(queryURLParams(URL)) </script>Copy the code

In the previous code, we created an A tag, and then we can get each part of the URL according to the attributes of the A tag. This is actually a bit similar to the route jump parameter of Vue.

Effect:

2.3 Split method

This method makes use of the split can be a character string split into an array of characteristics, cleverly will be each parameter segmentation out.

The code is as follows:

<script> let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100" function queryURLParams(URL) { // const url = location.search; // The project can use the search method directly to obtain the url "?" Let url = url.split ("?" ) [1]; let obj = {}; // declare the argument object let arr = url.split("&"); For (let I = 0; i < arr.length; i++) { let arrNew = arr[i].split("="); Obj [arrNew[0]] = arrNew[1]; } return obj; } console.log(queryURLParams(URL)) </script>Copy the code

In the upload code, if in the actual project, you can directly use location.search to get “?” The following string is split for demonstration purposes.

Effect:

2.4 URLSearchParams method

URLSearchParams method can make it very easy to obtain URL parameters, but there are certain compatibility problems, the official website explains as follows:

The URLSearchParams interface defines some useful methods for handling query strings for urls.

This interface provides a unique method for handling URL parameters. Here we will only describe how to obtain URL parameter values. For more details, you can refer to the official website.

The code is as follows:

<script> let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100" function queryURLParams(URL) { let url =  URL.split("?")[1]; const urlSearchParams = new URLSearchParams(url); const params = Object.fromEntries(urlSearchParams.entries()); return params } console.log(queryURLParams(URL)) </script>Copy the code

Here we basically parsed the parameters in just two lines of major code. Note that urlsearchparams.entries () returns an iterator, so we need to use the Object.fromentries () method to convert the list of key-value pairs into an Object.

For iteration protocols, you can refer to the official website: Iteration Protocols

Effect:

Compatibility:

You can see that our interface is not compatible with IE, the source of all Evil.

conclusion

Here introduced four methods to achieve URL link parameter value resolution, the most widely used should be split method. UrlSearchParams as a rising star, also gradually recognized by everyone, there are many ways to make it compatible with IE.