Using JavaScript to get the parameters of url delivery

Keywords: Javascript github

1. Get all parameters of url

We can get this part directly through window.location.search, which is the url parameter we need. When the url does not contain?, window.location.search returns undefined.

function getUrlVal(str){
    if(!str || str.indexOf('?') != 0) return false;
    var urlValArry = str.replace('?','').split('&');
    var urlValObject = {};
    for(var i in urlValArry){
        urlValObject[urlValArry[i].split('=')[0]] = urlValArry[i].split('=')[1];
    };
    return urlValObject;
};
//  https://github.com/search?utf8=%E2%9C%93&q=javascript
var urlStr = window.location.search.replace('?','');
console.log(getUrlVal(urlStr));  //output Object {utf8: "%E2%9C%93", q: "javascript"}

2. Get the key value (val) of the specified key name (name) in the url

function getOneVal(str,name){
    if(!str || str.indexOf('?') != 0) return false;
    var afterNameStr = str.replace('?','').split(name)[1];
    var strFirstSite = afterNameStr.indexOf('&');
    // Back to first&Location, if not'&'Return string length
    strFirstSite = (strFirstSite == -1) ? afterNameStr.length : strFirstSite
    var reslt = afterNameStr.slice(1,strFirstSite);
    return reslt;
};
//  'http://www.gotoplay.com/active?itemtype=sport&active=basketball&time=20160614&place=N230&peopleNum=657'
var urlStr = window.location.search;
console.log(getOneVal(urlStr,'time'))  //Output 20160614
console.log(getOneVal(urlStr,'peopleNum'))  //657

3. Use regular expressions to get parameters (powerful regularity is always desirable, and it is undoubtedly the most concise and elegant method)

(1) get a specified parameter

function getUrlParam(url,name){
    if(!name) return;
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
        r = url.substr(1).match(reg);
    if (r != null) {
        return (r[2]);
    }else{
        return null;
    }
}

(2) get all parameters

function parse_url(url){
    if(!url) return;
    var pattern = /(\w+)=(\w+)/ig;
    var parames = {};
    url.replace(pattern, function(a, b, c){
        parames[b] = c;
    });
    return parames;
}

Posted by hyp0r on Sun, 03 May 2020 10:49:25 -0700