拆分URL字符串以获取javascript中的每个参数值

时间:2014-05-05 20:24:46

标签: javascript

var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC"

如何拆分上面的字符串,以便获得每个参数的值?

3 个答案:

答案 0 :(得分:1)

您可以使用split函数来提取参数对。首先修剪包含?之前的内容,然后拆分&,然后在该循​​环之后分割=

var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";

var queryparams = url.split('?')[1];

var params = queryparams.split('&');

var pair = null,
    data = [];

params.forEach(function(d) {
    pair = d.split('=');
    data.push({key: pair[0], value: pair[1]});

});

请参阅jsfiddle

答案 1 :(得分:1)

试试这个:

var myurl = "journey?reference=123&line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var keyval = myurl.split('?')[1].split('&');
for(var x=0,y=keyval.length; x<y; x+=1)
console.log(keyval[x], keyval[x].split('=')[0], keyval[x].split('=')[1]);

答案 2 :(得分:0)

在JS中分割线应该使用:

var location = location.href.split('&');