开发者

How to parse URL safe query parameters into readable strings

开发者 https://www.devze.com 2023-03-06 00:59 出处:网络
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 quer

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 wo开发者_运维问答uld 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.


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.


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';
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消