我有一个带有一些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执行此操作?
当前回答
您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:
<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />
<script>
//...read the value on click
好吧,但说真的。。。我发现了这段代码,它似乎很有用:
http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/
function queryToJSON() {
var pairs = location.search.slice(1).split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.parse(JSON.stringify(result));
}
var query = queryToJSON();
其他回答
function gup() {
var qs = document.location.search;
qs = qs.split('+').join(' ');
var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs))
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
return params;
}
像这样使用
var params = gup()
然后
params.param1
params.param2
我尝试了很多不同的方法,但当我在URL中查找参数值时,这个尝试过的真正的正则表达式函数对我很有用,希望这有帮助:
var text='www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5'函数QueryString(项,文本){var foundString=text.match(新RegExp(“[\?\&]”+item+“=([^\&]*)(\&?)”,“i”));返回foundString?foundString[1]:foundString;}console.log(QueryString('c',文本));
使用类似QueuryString('param_name',url),并将返回值
平方米-3米-4米
这是一种只检查一个参数的简单方法:
示例URL:
http://myserver/action?myParam=2
Javascript示例:
var myParam = location.search.split('myParam=')[1]
如果URL中存在“myParam”。。。变量myParam将包含“2”,否则将未定义。
在这种情况下,可能需要一个默认值:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
更新:这更有效:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
即使URL中充满了参数,它也能正常工作。
来源
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})