7

Possible Duplicate:
Use the get parameter of the url in javascript

Suppose I have this url:

s = 'http://mydomain.com/?q=microsoft&p=next'

In this case, how do I extract "microsoft" from the string? I know that in python, it would be:

new_s = s[s.find('?q=')+len('?q='):s.find('&',s.find('?q='))]
Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

5

I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/

It allows you to do exactly what you are asking for:

var uri = 'http://mydomain.com/?q=microsoft&p=next';
var q = uri.queryKey['q'];
// q = 'microsoft'
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
2
(function(){

    var url = 'http://mydomain.com/?q=microsoft&p=next'
    var s = url.search.substring(1).split('&');

    if(!s.length) return;

    window.GET = {};

    for(var i  = 0; i < s.length; i++) {

        var parts = s[i].split('=');

        GET[unescape(parts[0])] = unescape(parts[1]);

    }

}())

Think this will work..

opHASnoNAME
  • 20,224
  • 26
  • 98
  • 143
  • 2
    `decodeURIComponent`. `escape`/`unescape` is almost always a mistake. – bobince Oct 26 '09 at 10:18
  • Also, this will NOT work with url being a string. Since it uses the method search, I suppose url should be window.location. Apart from these two issues, seems to work fine and importing a library to this task is surely an overkill. – fotanus Jan 09 '14 at 12:00