用javascript替換URL中的引數值

zybing發表於2021-09-09

今天遇到一個需要用javascript將url中的某些引數替換的需求,想起了不久前從先生的部落格中淘到了一個,正好可以藉此實現,程式碼整理如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//分析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
                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('/')
    };
}
 
//替換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;
            }
        }
        //原來沒有的引數則追加
        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;
}
 
//輔助輸出
function w(str) {
    document.write(str + "
"
);
}
 
var myURL = parseURL('');
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)   // = ''
 
var _newUrl = replaceUrlParams(myURL, { id: 101, m: "World", page: 1,"page":2 });
 
w("
新url為:"
)
w(_newUrl); //  

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/855/viewspace-2808432/,如需轉載,請註明出處,否則將追究法律責任。

相關文章