js to get the parameters in the link address

js to get the parameters in the link address

For example, the link address is: " http://blog.whuang.com/search?username=abc&age=26 "

I want to get the value "abc" of the username parameter

Method 1 :

core method

/**
     * Get the specified parameter value
     * @param url3
     * @param key
     * @returns {void|string|XML}
     */
    getParameter: function (url3, key) {
        var regExp = new RegExp('^.*[?&]' + key + '=([^&=?]*)&?.*$', '');
        var parameter = url3.replace(regExp, '$1');
        return parameter;
    }

 

Test code:

var url3="http://blog.whuang.com/search?username=abc&age=26";


        console.log(urlUtil.getParameter(url3,'age'));

url3="http://blog.whuang.com/search?username=abc&age=26";
console.log(urlUtil. getParameter(url3,'username'));

url3="http://blog.whuang.com/search?username=abc&age=26&callback=http%3A%2F%2Fc.b.com%3Fid%3D3";
console.log(urlUtil.getParameter(url3,'callback'));

url3="http://blog.whuang.com/search?username=&age=26";
console.log(urlUtil.getParameter(url3,'username'));

 

 

Method 2: Use the third-party library purl

Address: https://github.com/allmarkedup/purl

example:

this.options = {
        		username: purl().param('username') || '',
        		age: purl().param('age') || '',
                Key: ''
        	};

 See attachment for purl code

 

Method three:

/***
 * get request query string
 * @returns {{}}
 */
getQueryParams: function () {
    var i, allen, strs, keyName, keyValue,
        params = {},
        path = window.location.pathname,
        url = window.location.href;
    if (url.indexOf("?") > -1) {
        var index = url.indexOf("?");
        strs = url.substring(index + 1);
        strs = strs.split("&");
        ilen = strs.length;
        for (i = 0; i < ilen; i++) {
            var indexEqual = strs[i].indexOf('=');
            if (indexEqual == -1) {
                keyName = strs[i];
                keyValue = '';
            } else {
                keyName = strs[i].substring(0, indexEqual);
                keyValue = strs[i].substring(indexEqual + 1) || "";
            }

            if (keyName == "callback") keyValue = decodeURIComponent(keyValue);
            params[keyName] = keyValue;
        }
    }
    return params;
}

 Call method:

getQueryParams().username

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326922151&siteId=291194637