JS中获取URL参数
So you want to get a parameter from a URL? URL parameters (also called query string parameters or URL variables) can have lots of useful data including product info, user preferences, link referrals, and more.
Let’s get started!
Getting a URL Parameter
Let’s say you have the following URL:
1 | http://example.com/?product=shirt&color=blue&newuser&size=m |
Here’s a function to give you all the URL parameters as a neat object:
1 | function getAllUrlParams(url) { |
You’ll see how this works soon, but first, here are some usage examples:
1 | getAllUrlParams().product; // 'shirt' |
Things to Know Before Using This Function
- Our function assumes the parameters are separated by the
&
character, as indicated in the W3C specifications. However, the URL parameter format in general is not clearly defined, so you occasionally might see;
or&
as separators. - Our function still works if a parameter doesn’t have an equals sign or if it has an equals sign but no value.
- The values of duplicate parameters get put into an array.
If you just wanted a function you could drop into your code, you’re done now. If you’d like to understand how the function works, read on.
The following section assumes you know some JavaScript, including functions, objects, and arrays. If you need a refresher, check out the MDN JavaScript reference.
How the Function Works
Overall, the function takes a URL’s query string (the part after the ?
and before the #
) and spits out the data in a neat object.
First, this line says, if we’ve specified a URL, get everything after the question mark, but otherwise, just use the URL of the window:
1 | var queryString = url ? url.split('?')[1] : window.location.search.slice(1); |
Next, we’ll create an object to store our parameters:
1 | var obj = {}; |
If the query string exists, we’ll start parsing it. First we have to make sure to shave off the part starting from the #
since it’s not part of the query string:
1 | queryString = queryString.split('#')[0]; |
Now we can split the query string into its component parts:
1 | var arr = queryString.split('&'); |
That will give us an array that looks like this:
1 | ['product=shirt', 'color=blue', 'newuser', 'size=m'] |
Next we’ll loop through this array and split each item into a key and a value, which we’ll soon put into our object:
1 | var a = arr[i].split('='); |
Let’s assign the key and a value to individual variables. If there isn’t a parameter value, we’ll set it to true
to indicate that the parameter name exists. Feel free to change this depending on your use case:
1 | var paramName = a[0]; |
Optionally, you can set all parameter names and values to lowercase. That way, you can avoid situations where someone sends traffic to a URL with 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, feel free to omit this part:
1 | paramName = paramName.toLowerCase(); |
Next we need to deal with the various types of input we can receive in paramName
. This could be an indexed array, a non-indexed array, or a regular string.
If it’s an indexed array, we want the corresponding paramValue
to be an array, with the value inserted at the correct position. If it’s a non-indexed array, we want the corresponding paramValue
to be an array with the element pushed on to it. If it’s a string, we want to create a regular property on the object and assign the paramValue
to it, unless the property already exists, in which case we want to convert the existing paramValue
to an array and push the incoming paramValue
on to that.
To illustrate this, here’s some sample input, with the output we would expect:
1 | getAllUrlParams('http://example.com/?colors[0]=red&colors[2]=green&colors[6]=blue'); |
And here’s the code to implement the functionality:
1 | if (paramName.match(/\[(\d+)?\]$/)) { |
Finally, we return our object with the parameters and values.
If your URL has any encoded special characters like spaces (encoded as %20
), you can also decode them to get the original value like this:
1 | // assume a url parameter of test=a%20space |
Just be careful not to decode something that’s already decoded or else you can get a mistake, especially if percents are involved.
Anyways, congrats! Now you know how to get a URL parameter, and you might have picked up some other tricks along the way.
An Alternative for Modern Browsers
If you don’t need to support legacy browsers, you might like to look at the URLSearchParams interface, which defines utility methods to work with the query string of a URL:
1 | // URL is http://example.com/?product=shirt&color=blue&newuser&size=m |
It also provides familiar Object
methods like keys()
, values()
, and entries()
.
window.location对象所包含的属性
属性 | 描述 |
---|---|
hash | 从井号 (#) 开始的 URL(锚) |
host | 主机名和当前 URL 的端口号 |
hostname | 当前 URL 的主机名 |
href | 完整的 URL |
pathname | 当前 URL 的路径部分 |
port | 当前 URL 的端口号 |
protocol | 当前 URL 的协议 |
search | 从问号 (?) 开始的 URL(查询部分) |
小结
The code in this article works for the most common use cases where you would get a URL query parameter. If you’re working with any edge cases, such as uncommon separators or special formatting, then be sure to test and adjust accordingly.
If you want to do more with URLs, there are specific libraries available, such as jQuery URL plugin and Medialize URI.js. Since it’s basically string manipulation, it often makes sense just to use plain JavaScript. Whether you use your own code or go with a library, be sure to check everything and make sure it works for your use cases.
原文地址
https://www.sitepoint.com/get-url-parameters-with-javascript/