我有一个带有一些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执行此操作?
当前回答
我们可以以更简单的方式获取c参数值,而不必循环所有参数,请参见下面的jQuery获取参数。
1.获取参数值:
var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
url.match(**/(c=)[0-9A-Za-z-]+/ig**)[0].replace('c=',"")
(or)
url.match(**/(c=)[0-z-]+/ig**)[0].replace('c=',"")
以字符串形式返回
“m2-m3-m4-m5”
2.要替换参数值:
var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
url.replace(**/(c=)[0-9A-Za-z-]+/ig, "c=m2345"**)
其他回答
$_GET: function (param) {
var regex = new RegExp("(?:[?&]+" + param + "=)([^&]*)?", "i");
var match = regex.exec(window.location.href);
return match === null ? match : match[1];
}
获取单个参数值:
function getQueryParameter(query, parameter) {
return (window.location.href.split(parameter + '=')[1].split('&')[0]);}
正如在最新浏览器的第一个答案中提到的,我们可以使用新的URL api,然而,获取对象中的所有参数并使用它们的更一致的本地javascript简单解决方案可能是
例如,该类表示locationUtil
const locationSearch = () => window.location.search;
const getParams = () => {
const usefulSearch = locationSearch().replace('?', '');
const params = {};
usefulSearch.split('&').map(p => {
const searchParam = p.split('=');
const [key, value] = searchParam;
params[key] = value;
return params;
});
return params;
};
export const searchParams = getParams();
用法::现在可以在类中导入searchParams对象
url示例---https://www.google.com?key1=https://www.linkedin.com/in/spiara/&valid=true
import { searchParams } from '../somewhere/locationUtil';
const {key1, valid} = searchParams;
if(valid) {
console.log("Do Something");
window.location.href = key1;
}
这是有效的:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
我没有得到任何其他最好的答案。
使用道场。这里没有其他解决方案是如此简短或经过充分测试的:
require(["dojo/io-query"], function(ioQuery){
var uri = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = ioQuery.queryToObject(query);
console.log(queryObject.c); //prints m2-m3-m4-m5
});