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??

2
  • @Diodeus I would like a solution that saves them all to an array and that I can use repeatedly on lots of URLs Commented May 5, 2014 at 20:31
  • That is a secondary issue, once you've parsed the data and created the object. Commented May 5, 2014 at 20:35

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

to split line in JS u should use:

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

2 Comments

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 yeah! It's even better! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.