I have seen lots of jQuery examples where parameter size and name are unknown. My url is only going to ever have 1 string:
我见过很多jQuery示例,其中参数大小和名称未知。我的url只有一个字符串
http://example.com?sent=yes
I just want to detect:
我只是想检测一下
- Does
sent
exist? - 寄存在吗?
- Is it equal to "yes"?
- 它等于“是”吗?
33 个解决方案
#1
928
Best solution here.
最好的解决方案。
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,http://dummy.com/?technology=jquery&blog=jquerybyexample
.
假设URL是http://dummy.com/?technology=jquery&blog=jquerybyexample,那么就可以使用这个函数。
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
#2
152
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
jQuery代码片段获取作为参数存储在url中的动态变量,并将其存储为JavaScript变量,以便与脚本一起使用:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
example.com?param1=name¶m2=&id=6
example.com ? param1 = name¶m2 = id = 6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
示例参数与空间
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
#3
83
Solution from 2017
解决方案从2017年
We have: http://example.com?sent=yes
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sent exist?
寄存在吗?
searchParams.has('sent') // true
Is it equal to "yes"?
它等于“是”吗?
let param = searchParams.get('sent')
and then just compare it.
然后比较一下。
#4
69
I always stick this as one line. Now params has the vars:
我总是把它当作一行。params有vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
多行:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
作为一个函数
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
你可以把它作为:
getSearchParams() //returns {key1:val1, key2:val2}
or
或
getSearchParams("key1") //returns val1
#5
39
May be its too late. But this method is very easy and simple
可能为时已晚。但是这个方法非常简单
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet
更新需要url插件:plugins.jquery.com/url感谢-Ripounet
#6
28
Or you can use this neat little function, because why overcomplicated solutions?
或者你可以用这个简洁的小函数,为什么要用复杂的解呢?
function getQueryParam(param) {
location.search.substr(1)
.split("&")
.some(function(item) { // returns first occurence and stops
return item.split("=")[0] == param && (param = item.split("=")[1])
})
return param
}
which looks even better when simplified and onelined:
简化后看起来更好:
tl;dr one-line solution
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result: queryDict['sent'] // undefined or 'value'
But what if you have got encoded characters or multivalued keys?
You better see this answer: How can I get query string values in JavaScript?
您最好看到这个答案:如何在JavaScript中获得查询字符串值?
Sneak peak
偷偷高峰
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
#7
23
Yet another alternative function...
另一个替代函数…
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
#8
9
Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)
也许你想看看牙医JS ?(免责声明:我写了代码)
code:
代码:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
有了牙医JS,您基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),然后返回一个所有参数的HashMap。它也可定制以处理分隔符和所有。
Minified version < 1kb
简化版< 1 kb
#9
9
This one is simple and worked for me
这个很简单,对我很有用
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
so if your url is http://www.yoursite.com?city=4
如果你的url是http://www.yoursite.com?city=4
try this
试试这个
console.log($.urlParam('city'));
#10
5
function GetRequestParam(param)
{
var res = null;
try{
var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
var ar = qs.split('&');
$.each(ar, function(a, b){
var kv = b.split('=');
if(param === kv[0]){
res = kv[1];
return false;//break loop
}
});
}catch(e){}
return res;
}
#11
4
I hope this will help.
我希望这能有所帮助。
<script type="text/javascript">
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
$(window).load(function() {
var param = getParameters();
if (typeof param.sent !== "undefined") {
// Do something.
}
});
</script>
#12
3
There's this great library: https://github.com/allmarkedup/purl
这里有一个很棒的库:https://github.com/allmarkedup/purl。
which allows you to do simply
你能做的很简单吗
url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
if (sent == 'yes') { // sent is equal to yes
// ...
}
}
The example is assuming you're using jQuery. You could also use it just as plain javascript, the syntax would then be a little different.
这个例子假设您正在使用jQuery。您也可以将其作为普通的javascript使用,语法将略有不同。
#13
3
This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。
Example
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=*";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>
<span id="result"></span>
#14
2
Try this working demo http://jsfiddle.net/xy7cX/
尝试这个工作演示http://jsfiddle.net/xy7cX/
API:
API:
-
inArray
: http://api.jquery.com/jQuery.inArray/ - inArray:http://api.jquery.com/jQuery.inArray/
This should help :)
这应该有助于:)
code
代码
var url = "http://myurl.com?sent=yes"
var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
#15
2
This will give you a nice object to work with
这会给你一个很好的对象
function queryParameters () {
var result = {};
var params = window.location.search.split(/\?|\&/);
params.forEach( function(it) {
if (it) {
var param = it.split("=");
result[param[0]] = param[1];
}
});
return result;
}
And then;
然后;
if (queryParameters().sent === 'yes') { .....
#16
2
This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:
这是基于Gazoris的答案,但是URL解码了这些参数,以便在包含数字和字母以外的数据时使用:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://*.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
#17
2
So simple you can use any url and get value
你可以使用任何url来获取值
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Usage Example
使用的例子
// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2"
Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).
注意:如果一个参数多次出现(?first=value1&second=value2),您将得到第一个值(value1)和第二个值(value2)。
#18
2
There is another example with using URI.js library.
还有一个使用URI的例子。js库。
Example answers the questions exactly as asked.
示例完全按照要求回答问题。
var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';
// output results in readable form
// not required for production
if (sendExists) {
console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
if (urlParams.sent == 'yes') {
console.log('"Sent" param is equal to "yes"');
} else {
console.log('"Sent" param is not equal to "yes"');
}
} else {
console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
#19
1
Coffeescript version of Sameer's answer
萨米尔回答的咖啡稿
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++
#20
1
A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling
Sameer的回答稍微改进了一点,将解析缓存为闭包,以避免每次调用时对所有参数进行解析和循环
var getURLParam = (function() {
var paramStr = decodeURIComponent(window.location.search).substring(1);
var paramSegs = paramStr.split('&');
var params = [];
for(var i = 0; i < paramSegs.length; i++) {
var paramSeg = paramSegs[i].split('=');
params[paramSeg[0]] = paramSeg[1];
}
console.log(params);
return function(key) {
return params[key];
}
})();
#21
1
I use this and it works. http://codesheet.org/codesheet/NF246Tzs
我用这个,它就能工作。http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
#22
1
With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.
使用普通的JavaScript,您可以轻松地获取params (location.search),获取子字符串(不带?),并通过将其拆分为'&'将其转换为数组。
As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.
当您在urlParams中进行迭代时,您可以再次使用'='分割字符串,并将其作为对象添加到'params'对象[elmement[0]] = element[1]。超级简单,访问方便。
http://www.website.com/?error=userError&type=handwritten
http://www.website.com/?error=userError&type=handwritten
var urlParams = location.search.substring(1).split('&'),
params = {};
urlParams.forEach(function(el){
var tmpArr = el.split('=');
params[tmpArr[0]] = tmpArr[1];
});
var error = params['error'];
var type = params['type'];
#23
1
What if there is & in URL parameter like filename="p&g.html"&uid=66
如果有& in URL参数如filename="p&g.html"&uid=66怎么办
In this case the 1st function will not work properly. So I modified the code
在这种情况下,第一个函数不能正常工作。所以我修改了代码
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
#24
1
If you want to find a specific parameter from a specific url:
如果您想从特定的url查找特定的参数:
function findParam(url, param){
var check = "" + param;
if(url.search(check )>=0){
return url.substring(url.search(check )).split('&')[0].split('=')[1];
}
}
var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";
alert(findParam(url,"order_no"));
#25
0
Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:
诚然,我在回答一个过度回答的问题,但它的优点是:
-- Not depending on any outside libraries, including jQuery
——不依赖于任何外部库,包括jQuery
-- Not polluting global function namespace, by extending 'String'
——不要通过扩展“字符串”来污染全局函数名称空间
-- Not creating any global data and doing unnecessary processing after match found
——不创建任何全局数据,发现匹配后进行不必要的处理
-- Handling encoding issues, and accepting (assuming) non-encoded parameter name
——处理编码问题,并接受(假设)非编码参数名。
-- Avoiding explicit for
loops
——避免使用显式循环。
String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};
Then you'd use it as:
然后你可以这样使用:
var paramVal = "paramName".urlParamValue() // null if no match
#26
0
Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
另一个使用jQuery和JSON的解决方案,因此您可以通过对象访问参数值。
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
假设您的URL是http://example.com/?
After that it's only a matter of using the parameters like this:
之后,只需使用如下参数即可:
param.language
to return
返回
en
The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
最有用的用法是在页面加载时运行它,并使用全局变量来使用可能需要的参数。
If your parameter contains numeric values then just parse the value.
如果参数包含数值,则解析该值。
parseInt(param.page)
If there are no parameters param
will just be an empty object.
如果没有参数,param就是一个空对象。
#27
-1
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
#28
-1
use this
使用这个
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
#29
-1
Just wanted to show my codes:
只是想展示我的代码:
function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
#30
-1
var RequestQuerystring;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
RequestQuerystring = {};
while (match = search.exec(query))
RequestQuerystring[decode(match[1])] = decode(match[2]);
})();
RequestQuerystring is now an object with all you parameters
RequestQuerystring现在是一个包含所有参数的对象
#1
928
Best solution here.
最好的解决方案。
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,http://dummy.com/?technology=jquery&blog=jquerybyexample
.
假设URL是http://dummy.com/?technology=jquery&blog=jquerybyexample,那么就可以使用这个函数。
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
#2
152
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
jQuery代码片段获取作为参数存储在url中的动态变量,并将其存储为JavaScript变量,以便与脚本一起使用:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
example.com?param1=name¶m2=&id=6
example.com ? param1 = name¶m2 = id = 6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
示例参数与空间
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
#3
83
Solution from 2017
解决方案从2017年
We have: http://example.com?sent=yes
我们有:http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sent exist?
寄存在吗?
searchParams.has('sent') // true
Is it equal to "yes"?
它等于“是”吗?
let param = searchParams.get('sent')
and then just compare it.
然后比较一下。
#4
69
I always stick this as one line. Now params has the vars:
我总是把它当作一行。params有vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
多行:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
作为一个函数
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
你可以把它作为:
getSearchParams() //returns {key1:val1, key2:val2}
or
或
getSearchParams("key1") //returns val1
#5
39
May be its too late. But this method is very easy and simple
可能为时已晚。但是这个方法非常简单
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet
更新需要url插件:plugins.jquery.com/url感谢-Ripounet
#6
28
Or you can use this neat little function, because why overcomplicated solutions?
或者你可以用这个简洁的小函数,为什么要用复杂的解呢?
function getQueryParam(param) {
location.search.substr(1)
.split("&")
.some(function(item) { // returns first occurence and stops
return item.split("=")[0] == param && (param = item.split("=")[1])
})
return param
}
which looks even better when simplified and onelined:
简化后看起来更好:
tl;dr one-line solution
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result: queryDict['sent'] // undefined or 'value'
But what if you have got encoded characters or multivalued keys?
You better see this answer: How can I get query string values in JavaScript?
您最好看到这个答案:如何在JavaScript中获得查询字符串值?
Sneak peak
偷偷高峰
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
#7
23
Yet another alternative function...
另一个替代函数…
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
#8
9
Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)
也许你想看看牙医JS ?(免责声明:我写了代码)
code:
代码:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
有了牙医JS,您基本上可以在所有字符串上调用extract()函数(例如,document.URL.extract()),然后返回一个所有参数的HashMap。它也可定制以处理分隔符和所有。
Minified version < 1kb
简化版< 1 kb
#9
9
This one is simple and worked for me
这个很简单,对我很有用
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
so if your url is http://www.yoursite.com?city=4
如果你的url是http://www.yoursite.com?city=4
try this
试试这个
console.log($.urlParam('city'));
#10
5
function GetRequestParam(param)
{
var res = null;
try{
var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
var ar = qs.split('&');
$.each(ar, function(a, b){
var kv = b.split('=');
if(param === kv[0]){
res = kv[1];
return false;//break loop
}
});
}catch(e){}
return res;
}
#11
4
I hope this will help.
我希望这能有所帮助。
<script type="text/javascript">
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
$(window).load(function() {
var param = getParameters();
if (typeof param.sent !== "undefined") {
// Do something.
}
});
</script>
#12
3
There's this great library: https://github.com/allmarkedup/purl
这里有一个很棒的库:https://github.com/allmarkedup/purl。
which allows you to do simply
你能做的很简单吗
url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
if (sent == 'yes') { // sent is equal to yes
// ...
}
}
The example is assuming you're using jQuery. You could also use it just as plain javascript, the syntax would then be a little different.
这个例子假设您正在使用jQuery。您也可以将其作为普通的javascript使用,语法将略有不同。
#13
3
This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
这可能有点过分了,但是现在有一个非常流行的用于解析uri的库,叫做URI.js。
Example
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=*";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>
<span id="result"></span>
#14
2
Try this working demo http://jsfiddle.net/xy7cX/
尝试这个工作演示http://jsfiddle.net/xy7cX/
API:
API:
-
inArray
: http://api.jquery.com/jQuery.inArray/ - inArray:http://api.jquery.com/jQuery.inArray/
This should help :)
这应该有助于:)
code
代码
var url = "http://myurl.com?sent=yes"
var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
#15
2
This will give you a nice object to work with
这会给你一个很好的对象
function queryParameters () {
var result = {};
var params = window.location.search.split(/\?|\&/);
params.forEach( function(it) {
if (it) {
var param = it.split("=");
result[param[0]] = param[1];
}
});
return result;
}
And then;
然后;
if (queryParameters().sent === 'yes') { .....
#16
2
This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:
这是基于Gazoris的答案,但是URL解码了这些参数,以便在包含数字和字母以外的数据时使用:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://*.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
#17
2
So simple you can use any url and get value
你可以使用任何url来获取值
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Usage Example
使用的例子
// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2"
Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).
注意:如果一个参数多次出现(?first=value1&second=value2),您将得到第一个值(value1)和第二个值(value2)。
#18
2
There is another example with using URI.js library.
还有一个使用URI的例子。js库。
Example answers the questions exactly as asked.
示例完全按照要求回答问题。
var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';
// output results in readable form
// not required for production
if (sendExists) {
console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
if (urlParams.sent == 'yes') {
console.log('"Sent" param is equal to "yes"');
} else {
console.log('"Sent" param is not equal to "yes"');
}
} else {
console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
#19
1
Coffeescript version of Sameer's answer
萨米尔回答的咖啡稿
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++
#20
1
A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling
Sameer的回答稍微改进了一点,将解析缓存为闭包,以避免每次调用时对所有参数进行解析和循环
var getURLParam = (function() {
var paramStr = decodeURIComponent(window.location.search).substring(1);
var paramSegs = paramStr.split('&');
var params = [];
for(var i = 0; i < paramSegs.length; i++) {
var paramSeg = paramSegs[i].split('=');
params[paramSeg[0]] = paramSeg[1];
}
console.log(params);
return function(key) {
return params[key];
}
})();
#21
1
I use this and it works. http://codesheet.org/codesheet/NF246Tzs
我用这个,它就能工作。http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
#22
1
With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.
使用普通的JavaScript,您可以轻松地获取params (location.search),获取子字符串(不带?),并通过将其拆分为'&'将其转换为数组。
As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.
当您在urlParams中进行迭代时,您可以再次使用'='分割字符串,并将其作为对象添加到'params'对象[elmement[0]] = element[1]。超级简单,访问方便。
http://www.website.com/?error=userError&type=handwritten
http://www.website.com/?error=userError&type=handwritten
var urlParams = location.search.substring(1).split('&'),
params = {};
urlParams.forEach(function(el){
var tmpArr = el.split('=');
params[tmpArr[0]] = tmpArr[1];
});
var error = params['error'];
var type = params['type'];
#23
1
What if there is & in URL parameter like filename="p&g.html"&uid=66
如果有& in URL参数如filename="p&g.html"&uid=66怎么办
In this case the 1st function will not work properly. So I modified the code
在这种情况下,第一个函数不能正常工作。所以我修改了代码
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
#24
1
If you want to find a specific parameter from a specific url:
如果您想从特定的url查找特定的参数:
function findParam(url, param){
var check = "" + param;
if(url.search(check )>=0){
return url.substring(url.search(check )).split('&')[0].split('=')[1];
}
}
var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";
alert(findParam(url,"order_no"));
#25
0
Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:
诚然,我在回答一个过度回答的问题,但它的优点是:
-- Not depending on any outside libraries, including jQuery
——不依赖于任何外部库,包括jQuery
-- Not polluting global function namespace, by extending 'String'
——不要通过扩展“字符串”来污染全局函数名称空间
-- Not creating any global data and doing unnecessary processing after match found
——不创建任何全局数据,发现匹配后进行不必要的处理
-- Handling encoding issues, and accepting (assuming) non-encoded parameter name
——处理编码问题,并接受(假设)非编码参数名。
-- Avoiding explicit for
loops
——避免使用显式循环。
String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};
Then you'd use it as:
然后你可以这样使用:
var paramVal = "paramName".urlParamValue() // null if no match
#26
0
Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
另一个使用jQuery和JSON的解决方案,因此您可以通过对象访问参数值。
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
假设您的URL是http://example.com/?
After that it's only a matter of using the parameters like this:
之后,只需使用如下参数即可:
param.language
to return
返回
en
The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
最有用的用法是在页面加载时运行它,并使用全局变量来使用可能需要的参数。
If your parameter contains numeric values then just parse the value.
如果参数包含数值,则解析该值。
parseInt(param.page)
If there are no parameters param
will just be an empty object.
如果没有参数,param就是一个空对象。
#27
-1
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
#28
-1
use this
使用这个
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
#29
-1
Just wanted to show my codes:
只是想展示我的代码:
function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
#30
-1
var RequestQuerystring;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
RequestQuerystring = {};
while (match = search.exec(query))
RequestQuerystring[decode(match[1])] = decode(match[2]);
})();
RequestQuerystring is now an object with all you parameters
RequestQuerystring现在是一个包含所有参数的对象