0

I'm trying to get all parameters from an url.

Example:

http://domain.com/page?param1=values&param2=values2?param3=value3....&paramx=valuex

I am using this:

window.location.search.substring(1).split("&")

It works quite ok, except that all the parameters delimiters & are replaced by comma ,

Basically the parameters above are returned like this:

param1=values,param2=values2,param3=value3,....,paramx=valuex

Any idea how can can I get the parameters as they are?

David Dury
  • 5,537
  • 12
  • 56
  • 94
  • 5
    No, the `&` characters are not replaced by commas. You're misinterpreting the console output. The `.split()` function returns an **array**, not a string. – Pointy Aug 19 '14 at 19:04
  • That might help you : http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascriptà – Karl-André Gagnon Aug 19 '14 at 19:07
  • Sooo then I should use instead: `window.location.search.substring(1).split("?")` which will return an array of 2 elements and get the second element (1) ... right? – David Dury Aug 19 '14 at 19:07
  • In think the second `?` should be a `&` in your example (after `param2=values2`). And `window.location.search.substring(1).split("&")` was already the good solution. – Volune Aug 19 '14 at 19:46
  • expanding on other comments, here's a fiddle http://jsfiddle.net/vowxd0y2/ – BReal14 Aug 19 '14 at 19:47

1 Answers1

2

See this article on MDN. It answers your question. https://developer.mozilla.org/en-US/docs/Web/API/window.location

var oGetVars = {};
if (window.location.search.length > 1) {
  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
    aItKey = aCouples[nKeyId].split("=");
    oGetVars[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
  }
}
// alert(oGetVars.yourVar);
Gary Storey
  • 1,779
  • 2
  • 14
  • 19
  • Any particular reason this was down voted when it links to an article from an authoritative source that contains the EXACT code you are looking for? – Gary Storey Aug 19 '14 at 20:04
  • Example 7, 8, 9, etc – Gary Storey Aug 19 '14 at 20:06
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – EdChum Aug 19 '14 at 20:08
  • Thanks for the explantation – Gary Storey Aug 19 '14 at 20:08
  • By the way I didn't down vote you, your answer appeared in the SO low quality post queue, one of the options was the stock comment I left, you will find that most down voters don't leave a comment – EdChum Aug 19 '14 at 20:10
  • Thanks for the information. I have edited my original answer and I will remember this in the future. – Gary Storey Aug 19 '14 at 20:12