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

How can I split the string above so that I get each parameter's value??

user3605739
  • 495
  • 3
  • 6
  • 17

3 Answers3

3

You could use the split function to extract the parameter pairs. First trim the stuff before and including the ?, then split the & and after that loop though that and split the =.

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]});

});

See jsfiddle

Imperative
  • 3,138
  • 2
  • 25
  • 40
2

Try this:

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]);
Alex Shilman
  • 1,547
  • 1
  • 11
  • 15
0

to split line in JS u should use:

var location = location.href.split('&');
Nikita_Sp
  • 94
  • 4
  • Instead of location.href, it would be easier to use location.search which will only return the question mark and everything after it. Then just chop off the first character using a substring. – tomysshadow May 05 '14 at 20:48
  • @tomysshadow yeah! It's even better! Thanks! – Nikita_Sp May 06 '14 at 12:20