0

I'm looking for a way to extract the query parameters and their corresponding values from a url.

For example. If I have the URL: http://example.com/home?key=value

How can I find the value of key

Justin Taddei
  • 2,142
  • 1
  • 16
  • 30
pradeep
  • 45
  • 7

1 Answers1

0

Use this function. It's inspired from riot.route.query()

getQuery( [url] ) returns an object containing every key, value pair in the query of window.location.href or the optional url parameter.

var iFrameUrls = [
    'http://www.kk.com/home/add.do?select=inputText',
    '?select=verifyText&this=foo%20bar',
    'http://www.kk.com/home/add.do?select=confirmText'
    ];

function getQuery(url) {
    var query = {},
        href = url || window.location.href;
        
    href.replace(/[?&](.+?)=([^&#]*)/g, function (_, key, value) {
        query[key] = decodeURI(value).replace(/\+/g, ' ');
    });
    
    return query;
}

for (var i = 0, l = iFrameUrls.length; i < l; i++)
  console.log( getQuery( iFrameUrls[i] ) );
Justin Taddei
  • 2,142
  • 1
  • 16
  • 30
  • hey Thank you. But we have multiple pages whose query parameter changes based on the page we are in (select=inputText, select=enterText) so we need one code to capture the current value from to find on which page we are in – pradeep Mar 01 '17 at 14:36
  • Can you provide an example of what you want to retrieve from the URL? – Justin Taddei Mar 01 '17 at 15:11
  • www.kk.com/home/add.do?select=inputText | www.kk.com/home/add.do?select=verifyText | www.kk.com/home/add.do?select=confirmText | We have some steps in iframe with the above sample URLs. 1st page asks for input,2nd asks us to verify and 3rd gives us confirmation. Now if are able to capture the Target values from the iFrame URL we will know in which step the user is in – pradeep Mar 01 '17 at 15:14
  • So you're looking for whether `select` = `inputText`, `enterText` etc.? – Justin Taddei Mar 01 '17 at 15:21
  • Yes Exactly! Justin – pradeep Mar 01 '17 at 15:29
  • Because you're using an `iframe`, you'll need to use `document.querySelector('#iframeID').src` as the `url` parameter. Unless the script executing `getQuery` is in the `iframe`—than just use `getQuery()` – Justin Taddei Mar 01 '17 at 15:46
  • Yeah! Thanks Justin – pradeep Mar 01 '17 at 19:47
  • @pradeep My pleasure. – Justin Taddei Mar 01 '17 at 19:48