7
\$\begingroup\$

I have a URL in this format:

http://localhost:57279/AssociateCaseDetails?UId=176948&caseID=1123

I need the values of UId and CaseID:

var UId =window.location.href.split("?")[1].split("&")[0].split("=")[1];

It’s working, but is there a better way to access the same, given the same URL?

unor
2,67315 silver badges24 bronze badges
asked Mar 25, 2015 at 5:33
\$\endgroup\$

1 Answer 1

9
\$\begingroup\$

Instead of splitting from the ?, you can use location.search. It returns everything from (and including) the ? until the end of the query string. If there's a hash, it stops right before #.

Since it includes the ?, you can do location.search.slice(1) to get the string without the ?.

Then you can do:

var queries = location.search
 .slice(1)
 .split('&')
 .reduce(function(carry, query){
 var queryPair = query.split('=');
 carry[queryPair[0]] = queryPair[1];
 return carry;
 },{});

From ?foo=foovalue&bar=barvalue, you can get something like:

var queries = {
 foo: 'foovalue',
 bar: 'barvalue',
}

I have to add that this only works for 1-level query string. Stuff like arrays (foo[]=foo0&foo[]=foo1) and key-value pairs (foo[bar]=bar&foo[baz]=baz) isn't covered in this logic.

answered Mar 25, 2015 at 8:22
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.