2012-01-01 36 views
4

我試圖編寫一個函數,它將從javascript中的url中刪除查詢參數。我想我使用正則表達式,但我不知道我是否錯過了任何東西。另外,我不能動搖那種感覺,可能有更好的方法來做到這一點,這並不涉及我半天正在用正則表達式搞亂並冒着後來發現我沒有采取某種角落的風險情況考慮在內。從javascript中的URL中刪除查詢參數

remove_query_argument = function(url, arg){ 

    var query_arg_regex; 

    // Remove occurences that come after '&' symbols and not the first one after the '?' 
    query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig'); 
    url = url.replace(query_arg_regex, ''); 

    // remove the instance that the argument to remove is the first one 
    query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i'); 
    url = url.replace(query_arg_regex, function (match, capture) { 
     if(capture != '&'){ 
      return ''; 
     }else{ 
      return '?' 
     } 

    }); 

    return url; 
} 

有沒有人看到這個代碼的任何問題,或者想建議一個更好的實現或方法來解決這個問題?

謝謝!

var removeQueryFields = function (url) { 
    var fields = [].slice.call(arguments, 1).join('|'), 
     parts = url.split(new RegExp('[&?](' + fields + ')=[^&]*')), 
     length = parts.length - 1; 
    return parts[0] + '?' + (length ? parts[length].slice(1) : ''); 
} 

一些例子:

+0

這將是更好的地方,我認爲 - http://codereview.stackexchange.com/ – emaillenin 2012-01-01 09:14:23

回答

3

如果你有很多的URL相關的操作,你最好試試這個真棒js庫https://github.com/medialize/URI.js

+0

是的,看起來像這樣會節省我大量的時間: http://medialize.github.com/URI.js/docs.html#search-remove – 2012-01-01 20:08:45

2

給出一個percent-encoded URL,下面的函數將它的查詢字符串中刪除字段值對

var string = 'http://server/path/program?f1=v1&f2=v2'; 
removeQueryFields(string, 'f1');  // 'http://server/path/program?f2=v2' 
removeQueryFields(string, 'f2');  // 'http://server/path/program?f1=v1' 
removeQueryFields(string, 'f1', 'f2'); // 'http://server/path/program' 
+1

這將下降當最後一個參數被刪除時,URL上的任何片段。 – 2012-01-01 21:32:55

+0

因爲他的RegExp是錯誤的,當有一個空值參數時,它不會工作。我使用了這個腳本,並在意識到它沒有工作時修復它: new RegExp('[&?]('+ fields +')=。* [^&]。*')) – aleation 2012-12-18 09:39:50