我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要获得的全部价值c
。我尝试读取该URL,但只有m2
。如何使用JavaScript执行此操作?
我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要获得的全部价值c
。我尝试读取该URL,但只有m2
。如何使用JavaScript执行此操作?
简单的方法
function getParams(url){
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
然后像getParams(url)这样称呼它
// http:localhost:8080/path?param_1=a¶m_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"
最短的方法:
new URL(location.href).searchParams.get("my_key");
对于像index.html?msg = 1这样的“ 单参数值”,请使用以下代码,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search.substring(1);
var varArray = queryString.split("="); //eg. index.html?msg=1
var param1 = varArray[0];
var param2 = varArray[1];
}
对于所有参数值,请使用以下代码,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search;
var varArray = queryString.split("&");
for (var i=0;i<varArray.length;i++) {
var param = varArray[i].split("=");
//parameter-value pair
}
}
这是我的解决方案。正如Andy E在回答此问题时所建议的那样,如果脚本重复构建各种正则表达式字符串,运行循环等只是为了获得单个值,则对脚本的性能不利。因此,我想出了一个更简单的脚本,该脚本在单个对象中返回所有GET参数。您应该只调用一次,将结果分配给变量,然后在将来的任何时候使用适当的键从该变量中获取所需的任何值。请注意,它还负责URI解码(即类似%20的事情),并用空格替换+:
function getUrlQueryParams(url) {
var queryString = url.split("?")[1];
var keyValuePairs = queryString.split("&");
var keyValue = [];
var queryParams = {};
keyValuePairs.forEach(function(pair) {
keyValue = pair.split("=");
queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
return queryParams;
}
因此,这是脚本的一些测试供您查看:
// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".
// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".
// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
或者,如果您不想重新发明URI解析轮,请使用URI.js
要获取名为foo的参数的值:
new URI((''+document.location)).search(true).foo
那是什么
这是一个小提琴。... http : //jsfiddle.net/m6tett01/12/
ECMAScript 6解决方案:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i<arrURLParams.length; i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0; i<arrURLParams.length; i++)
{
if (arrParamNames[i] == paramName)
{
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
使用URLSearchParams的超级简单方法。
function getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
目前,Chrome,Firefox,Safari,Edge和其他版本支持该功能。
我写了一个更简单优雅的解决方案。
var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
我很久以前就发现这很简单:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
然后这样称呼它:
var fType = getUrlVars()["type"];
JavaScript 本身没有内置处理查询字符串参数的内容。
在(现代)浏览器中运行的代码可以使用URL
对象(它是浏览器提供给JS的API的一部分):
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
For older browsers (including Internet Explorer), you can use this polyfill or the code from the original version of this answer that predates URL
:
You could access location.search
, which would give you from the ?
character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = decodeURIComponent(value);
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], decodeURIComponent(value)];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(decodeURIComponent(value));
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
All we’d need to do to get the parameters id and page are to call this:
The Code will be: