As a front-end developer, we often need to operate and process URLs. The most common one is to obtain the parameter values carried in the URL link. Friends who use framework development may find this very simple, because the framework provides many methods for us to conveniently obtain the parameters carried by the URL link. But sometimes we cannot rely on the framework and need to use native JS to obtain parameters. This is also a question often encountered in interviews. Today we will tear up the code by hand and use native JS to obtain the URL link parameter values.
There are several ways to obtain URL link parameters using native JS. Today we will explain the common ones in turn:
using regular matching,
using the a tag built-in method,
using the split method,
using the URLSearchParams method
This is a very standard method. The key point is that we need to understand regular expressions.
The code is as follows:
<script> //Use regular expression let url = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100" // // Return parameter object function queryURLParams(url) { let pattern = /(w+)=(w+)/ig; //Define regular expression let parames = {}; //Define parameter object url.replace(pattern, ($, $1, $2) => { parames[$1] = $2; }); return parameters; } console.log(queryURLParams(url)) </script>
The focus of the above code is the definition of regular expressions and the use of the replace method, among which
1, and $2 respectively represent name=elephant, name, elephant, and so on. You can learn it by yourself for more detailed usage of replace combined with regular expressions.
Realization effect:
is rarely used by people, because after all, it has a bit of a black technology meaning. Its principle is mainly to use the a tag to obtain 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. Create a tag let link = document.createElement('a'); link.href = url; let searchUrl = link.search.substr(1); // Get the string after the question mark let hashUrl = link.hash.substr(1); // Get the value after # let obj = {}; // Declare parameter object/ / 2. Store hashUrl in the object? obj['HASH'] = hashUrl : null; // #Is there a value behind 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>
In the above code, an a tag is first created, and then each part of the url can be obtained based on the attributes of the a tag. This is actually somewhat similar to Vue's routing jump to obtain parameters.
Realization effect:
This method takes advantage of the fact that split can divide a string into an array based on a certain character, and cleverly divides each parameter.
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; // In the project, you can directly obtain the string after the "?" character in the url through the search method let url = URL.split("?")[1]; let obj = {}; // Declare parameter object let arr = url.split("&"); // Split into array with ampersand for (let i = 0; i < arr.length; i++) { let arrNew = arr[i].split("="); // Split into arrays with "=" obj[arrNew[0]] = arrNew[1]; } return obj; } console.log(queryURLParams(URL)) </script>
If the upload code is used in an actual project, you can directly use location.search to obtain the string after "?". For the convenience of demonstration, split is used to divide the following.
Realization effect:
The URLSearchParams method allows us to obtain URL parameters very conveniently, but there are certain compatibility issues. The official website explains it as follows:
The URLSearchParams interface defines some practical methods to process URL query strings.
This interface provides special methods for us to process URL parameters. Here we only introduce how to obtain URL parameter values. For more detailed usage, 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>
Here we basically use only two lines of main code to implement parameter parsing. It should be noted that urlSearchParams.entries() returns an iteration protocol iterator, so we need to use the Object.fromEntries() method to convert the list of key-value pairs into an object.
Regarding the iteration protocol, you can refer to the official website:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols
to achieve the effect:
compatibility:
You can see that our interface is not compatible with IE, the source of all evil.
Four methods are introduced here to realize the parsing of URL link parameter values. Among them, the most widely used one is the split method. As a rising star, urlSearchParams is gradually recognized by everyone, and there are many ways to make it compatible with IE.
[Recommended related video tutorials: web front-end]
The above is how to obtain URL parameters in JavaScript? For detailed explanations of 4 common methods, please pay attention to other related articles on the PHP Chinese website for more information!