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='))]
0

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

decodeURIComponent. escape/unescape is almost always a mistake.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.