bloudermilk
bloudermilk

Reputation: 18109

How to parse URL safe query parameters into readable strings

I found one library, jQuery URL Parser, which seems to be full-featured as far as parsing out the various segments of a URL. I'm trying to go one step further though, and parse the values of the query parameters.

For example, given the URL "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=rm+-rf+%2F" I'd like to get "rm -rf /" for the q parameter. Any suggestions would be greatly appreciated.

As a side note, I'm not operating on the URL of the current page so any location magic doesn't apply.

Upvotes: 0

Views: 1505

Answers (2)

Shlomi Komemi
Shlomi Komemi

Reputation: 5545

you can use your own small lightweight code to do just that :

    function getParam(url, param) {
        if (!url.indexOf('?')) {
            return 'undefined';
        }
        url = url.split('?')[1];
        var arr = url.split('&');
        for (var i = 0; i < arr.length; i++) {
            var key = arr[i].split('=')[0], val = arr[i].split('=')[1];
            if (key === param) {
                return val;
            }
        }
        return 'undefined';
    }

Upvotes: 0

mellamokb
mellamokb

Reputation: 56769

It looks as though the library you referenced can indeed retrieve query string values as given under the section called Query string parameters:

The .param() method is used to return the values of querystring parameters.

Pass in a string to access that parameter's value:

$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue' If no argument is passed in it will return an object literal containing a key:value map of all the querystring parameters.

$.url('http://allmarkedup.com?sky=blue&grass=green').param(); // returns { 'sky':'blue', 'grass':'green' } Note that the .param() method will work on both ampersand-split and semicolon-split querystrings.

Upvotes: 2

Related Questions