Replace the sample code for parameter values in the URL with javascript

  • 2020-03-30 01:34:30
  • OfStack

Today, I met a requirement to replace some parameters in the url with javascript. I remembered that I found a parseUrl function from the Internet not long ago, which can be realized by this. The code is as follows:

//Analysis of the url
function parseURL(url) { 
    var a = document.createElement('a'); 
    a.href = url; 
    return { 
        source: url, 
        protocol: a.protocol.replace(':', ''), 
        host: a.hostname, 
        port: a.port, 
        query: a.search, 
        params: (function () { 
            var ret = {}, 
            seg = a.search.replace(/^?/, '').split('&'), 
            len = seg.length, i = 0, s; 
            for (; i < len; i++) { 
                if (!seg[i]) { continue; } 
                s = seg[i].split('='); 
                ret[s[0]] = s[1]; 
            } 
            return ret; 

        })(), 
        file: (a.pathname.match(//([^/?#]+)$/i) || [, ''])[1], 
        hash: a.hash.replace('#', ''), 
        path: a.pathname.replace(/^([^/])/, '/$1'), 
        relative: (a.href.match(/tps?://[^/]+(.+)/) || [, ''])[1], 
        segments: a.pathname.replace(/^//, '').split('/') 
    }; 
} 

//Replace the parameter value of the same name in myUrl
function replaceUrlParams(myUrl, newParams) { 
    

    for (var x in newParams) { 
        var hasInMyUrlParams = false; 
        for (var y in myUrl.params) { 
            if (x.toLowerCase() == y.toLowerCase()) { 
                myUrl.params[y] = newParams[x]; 
                hasInMyUrlParams = true; 
                break; 
            } 
        } 
        //The original parameters are appended
        if (!hasInMyUrlParams) { 
            myUrl.params[x] = newParams[x]; 
        } 
    } 
    var _result = myUrl.protocol + "://" + myUrl.host + ":" + myUrl.port + myUrl.path + "?"; 

    for (var p in myUrl.params) { 
        _result += (p + "=" + myUrl.params[p] + "&"); 
    } 

    if (_result.substr(_result.length - 1) == "&") { 
        _result = _result.substr(0, _result.length - 1); 
    } 

    if (myUrl.hash != "") { 
        _result += "#" + myUrl.hash; 
    } 
    return _result; 
} 

//Aux output
function w(str) { 
    document.write(str + "<BR>"); 
} 

var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top'); 
w("myUrl.file = " + myURL.file)     // = 'index.html'  
w("myUrl.hash = " + myURL.hash)     // = 'top'   
w("myUrl.host = " + myURL.host)     // = 'abc.com' 
w("myUrl.query = " + myURL.query)    // = '?id=255&m=hello' 
w("myUrl.params = " + myURL.params)   // = Object = { id: 255, m: hello }   
w("myUrl.path = " + myURL.path)     // = '/dir/index.html'   
w("myUrl.segments = " + myURL.segments) // = Array = ['dir', 'index.html'] 
w("myUrl.port = " + myURL.port)     // = '8080'   
w("myUrl.protocol = " + myURL.protocol) // = 'http'   
w("myUrl.source = " + myURL.source)   // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top' 

var _newUrl = replaceUrlParams(myURL, { id: 101, m: "World", page: 1,"page":2 }); 

w("<BR> new url To: ") 
w(_newUrl); //http://abc.com:8080/dir/index.html?id=101&m=World&page=2#top    

Related articles: