Home >Web Front-end >JS Tutorial >How to Get URL Parameters with JavaScript
URL parameters (also known as query string parameters or URL variables) are used to send small amounts of data between pages or between the client and the server via URL. They can contain various useful information such as search queries, link recommendations, product information, user preferences, and more.
This article will show you how to parse and manipulate URL parameters using JavaScript.
Key Points
get()
to return the first value associated with a given search parameter; has()
to check if a specific parameter exists ;getAll()
is used to return all values associated with a specific parameter. Get URL parameters
This has become much easier in modern browsers, thanks to the URLSearchParams interface. It defines a series of utility methods to handle query strings for URLs.
Suppose our URL is https://example.com/?product=shirt&color=blue&newuser&size=m
, we can use window.location.search
to get the query string:
<code class="language-javascript">const queryString = window.location.search; console.log(queryString); // ?product=shirt&color=blue&newuser&size=m</code>
Then we can parse the parameters of the query string using URLSearchParams:
<code class="language-javascript">const urlParams = new URLSearchParams(queryString);</code>
We can then call any of its methods on the result.
For example, URLSearchParams.get()
will return the first value associated with the given search parameter:
<code class="language-javascript">const product = urlParams.get('product'); console.log(product); // shirt const color = urlParams.get('color'); console.log(color); // blue const newUser = urlParams.get('newuser'); console.log(newUser); // 空字符串</code>
Other useful methods
You can use URLSearchParams.has()
to check if a specific parameter exists:
<code class="language-javascript">console.log(urlParams.has('product')); // true console.log(urlParams.has('paymentmethod')); // false</code>
You can use URLSearchParams.getAll()
to return all values associated with a specific parameter:
<code class="language-javascript">console.log(urlParams.getAll('size')); // ['m'] // 以编程方式添加第二个size参数。 urlParams.append('size', 'xl'); console.log(urlParams.getAll('size')); // ['m', 'xl']</code>
URLSearchParams also provides some commonly used object iterator methods that allow you to iterate over its keys, values, and entries:
<code class="language-javascript">const keys = urlParams.keys(), values = urlParams.values(), entries = urlParams.entries(); for (const key of keys) console.log(key); // product, color, newuser, size for (const value of values) console.log(value); // shirt, blue, , m for (const entry of entries) { console.log(`${entry[0]}: ${entry[1]}`); } // product: shirt // color: blue // newuser: // size: m</code>
Browser support
The browser support for URLSearchParams is good. At the time of writing, it is supported by all major browsers.
If you must support older browsers (such as Internet Explorer), you can use polyfill. or , you can continue reading the rest of this tutorial and learn how to write one yourself.
Writing your own query string parsing function
Let's continue using the URL used in the previous section:
<code class="language-javascript">const queryString = window.location.search; console.log(queryString); // ?product=shirt&color=blue&newuser&size=m</code>
This is a function that provides all URL parameters as a concise object:
<code class="language-javascript">const urlParams = new URLSearchParams(queryString);</code>
You will see how it works soon, but first, here are some usage examples:
<code class="language-javascript">const product = urlParams.get('product'); console.log(product); // shirt const color = urlParams.get('color'); console.log(color); // blue const newUser = urlParams.get('newuser'); console.log(newUser); // 空字符串</code>
(The CodePen demonstration part is omitted here because CodePen code cannot be embedded directly)
Things to know before using this function
&
characters, as shown in the W3C specification. However, the URL parameter format is usually not well defined, so you may occasionally see ;
or &
as delimiters. If you only need a function that you can put into your code, then it's done now. If you want to understand how a function works, read on.
The next section assumes that you understand some JavaScript, including functions, objects, and arrays. If you need a review, check out the MDN JavaScript reference.
How does the function work
In general, this function takes the query string of the URL (the part after the question mark ?
and before the pound mark #
) and outputs the data in a concise object form.
First of all, this line of code means that if we specify a URL, we get everything after the question mark, otherwise, just use the URL of the window:
<code class="language-javascript">console.log(urlParams.has('product')); // true console.log(urlParams.has('paymentmethod')); // false</code>
Next, we will create an object to store our parameters:
<code class="language-javascript">console.log(urlParams.getAll('size')); // ['m'] // 以编程方式添加第二个size参数。 urlParams.append('size', 'xl'); console.log(urlParams.getAll('size')); // ['m', 'xl']</code>
If a query string exists, we will start parsing it. First, we have to make sure to remove the part that starts with #
, as it is not part of the query string:
<code class="language-javascript">const keys = urlParams.keys(), values = urlParams.values(), entries = urlParams.entries(); for (const key of keys) console.log(key); // product, color, newuser, size for (const value of values) console.log(value); // shirt, blue, , m for (const entry of entries) { console.log(`${entry[0]}: ${entry[1]}`); } // product: shirt // color: blue // newuser: // size: m</code>
Now we can split the query string into its components:
<code>http://example.com/?product=shirt&color=blue&newuser&size=m</code>
This will give us an array as shown below:
<code class="language-javascript">function getAllUrlParams(url) { // 从url(可选)或窗口获取查询字符串 var queryString = url ? url.split('?')[1] : window.location.search.slice(1); // 我们将在这里存储参数 var obj = {}; // 如果存在查询字符串 if (queryString) { // #后面的内容不是查询字符串的一部分,所以去掉它 queryString = queryString.split('#')[0]; // 将查询字符串拆分为其组成部分 var arr = queryString.split('&'); for (var i = 0; i < arr.length; i++) { // 分离键和值 var a = arr[i].split('='); // 设置参数名称和值(如果为空则使用'true') var paramName = a[0]; var paramValue = typeof (a[1]) === 'undefined' ? true : a[1]; // (可选)保持大小写一致 paramName = paramName.toLowerCase(); if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase(); // 如果paramName以方括号结尾,例如colors[]或colors[2] if (paramName.match(/\[(\d+)?\]$/)) { // 如果不存在,则创建键 var key = paramName.replace(/\[(\d+)?\]/, ''); if (!obj[key]) obj[key] = []; // 如果它是索引数组,例如colors[2] if (paramName.match(/\[\d+\]$/)) { // 获取索引值并在适当的位置添加条目 var index = /\[(\d+)\]/.exec(paramName)[1]; obj[key][index] = paramValue; } else { // 否则将值添加到数组的末尾 obj[key].push(paramValue); } } else { // 我们正在处理字符串 if (!obj[paramName]) { // 如果不存在,则创建属性 obj[paramName] = paramValue; } else if (obj[paramName] && typeof obj[paramName] === 'string') { // 如果属性存在并且是字符串,则将其转换为数组 obj[paramName] = [obj[paramName]]; obj[paramName].push(paramValue); } else { // 否则添加属性 obj[paramName].push(paramValue); } } } } return obj; }</code>
Next we will iterate over this array and split each item into keys and values, which we will soon put into our object:
<code class="language-javascript">getAllUrlParams().product; // 'shirt' getAllUrlParams().color; // 'blue' getAllUrlParams().newuser; // true getAllUrlParams().nonexistent; // undefined getAllUrlParams('http://test.com/?a=abc').a; // 'abc'</code>
Let's assign keys and values to a single variable. If there is no parameter value, we will set it to true
to indicate that the parameter name exists. You can change this setting as you like according to your use case:
<code class="language-javascript">var queryString = url ? url.split('?')[1] : window.location.search.slice(1);</code>
Optionally, you can set all parameter names and values to lowercase. This way, you can avoid situations where someone is sending traffic to the URL, such as example=TRUE
instead of example=true
and your script breaks. (I've seen this happen.) However, if your query string needs to be case sensitive, you can omit this part at will:
<code class="language-javascript">const queryString = window.location.search; console.log(queryString); // ?product=shirt&color=blue&newuser&size=m</code>
Next, we need to process various types of inputs that we can receive in paramName
. This could be an indexed array, a non-indexed array, or a normal string.
If it is an index array, we want the corresponding paramValue
to be an array and insert the value into the correct position. If it is a non-indexed array, we want the corresponding paramValue
to be an array and push the elements into it. If it is a string, we want to create a regular property on the object and assign paramValue
to it, unless the property already exists, in which case we want to add the existing Convert to an array and push the passed in paramValue
into that array. paramValue
<code class="language-javascript">const urlParams = new URLSearchParams(queryString);</code>This is the code that implements this function:
<code class="language-javascript">const product = urlParams.get('product'); console.log(product); // shirt const color = urlParams.get('color'); console.log(color); // blue const newUser = urlParams.get('newuser'); console.log(newUser); // 空字符串</code>Finally, we return our object containing the parameters and values.
If your URL has any encoded special characters, such as spaces (encoded as
), you can also decode them to get the original value as shown below:
<code class="language-javascript">console.log(urlParams.has('product')); // true console.log(urlParams.has('paymentmethod')); // false</code>Just be careful not to decode what has been decoded or your script will go wrong, especially if percentages are involved.
Anyway, congratulations! Now you know how to get URL parameters and hope to learn other tips along the way.
Conclusion
The code in this article is suitable for most common use cases where you get URL query parameters. If you deal with any edge cases, such as uncommon separators or special formats, be sure to test and adjust accordingly.If you want to do more with the URL, you can use specific libraries such as query-string and Medialize URI.js. However, since it's basically a string operation, it makes more sense to use pure JavaScript in general. Whether you use your own code or use a library, be sure to check everything and make sure it works for your use case.
If you like playing with strings, check out our article on splitting strings into substrings, converting strings into numbers, and converting numbers into strings and ordinal numbers. For more in-depth JavaScript knowledge, read our book "JavaScript: From Newbie to Ninja, Second Edition".
(The FAQs part is omitted here because the content is highly duplicated from the text)
The above is the detailed content of How to Get URL Parameters with JavaScript. For more information, please follow other related articles on the PHP Chinese website!