首頁  >  文章  >  web前端  >  用javascript替換URL中的參數值範例程式碼_javascript技巧

用javascript替換URL中的參數值範例程式碼_javascript技巧

WBOY
WBOY原創
2016-05-16 17:02:161311瀏覽

今天遇到一個需要用javascript將url中的某些參數替換的需求,想起了不久前從網上淘到了一個parseUrl函數,正好可以藉此實現,代碼整理如下:

複製程式碼 程式碼如下:

//分析url
function parseURL(url) {
    var a = document.createElement('a');
    a.href = url; >        來源:url,
        協定:a.protocol.replace(':', ''),
             查詢:a.search ,
        params: (function () {
            var ret = {}, ),
len = seg.length, i = 0, s;
            for (; i                   s = seg[i]. split('=');
               ret[s[0]] = s[1];
        >
        })( ),
        檔: ( a.pathname.match(//([^/?#] )$/i) || [, ''])[1],
        哈希: a.hash.replace ('#', '' ),
        路徑:a.pathname.replace(/^([^/])/, '/$1'),
        相對:(a.href.match(/tps) ?[ /] (. )/) || [, ''])[1],
        段:a.pathname.replace(/^//, '').split('/' )
    };
}

//替換myUrl中的同名參數值
function ReplaceUrlParams(myUrl, newParams) {
    /*
  >        for (var y in newParams) {
            if (x.toLowerCase() =   params[x] = newParams[y];
            }
}
    }
    */

    for (var x in newParams) {
      rl.params) {
            if ( x.toLowerCase() == y.toLowerCase()) {
                myUrl.params[y] = new s = true;
                休息中;
           🎜>        // 原先的參數則追加
        if (!hasInMyUrlParams) {
        }
    }
    var _result = myUrl.protocol "://" myUrl.host ":" myUrl.port myUrl.path "?";

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

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

    if (myUrl.hash != "") {
       🎜>}

//輔助輸出
function w(str) {
    document.write(str "
");
}

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)     // = '上方'  
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("
新網址為:")
w(_newUrl); //http://abc.com:8080/dir/index.html?id=101&m=World&page=2#top   

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn