2017-06-12 69 views
1

我正在尋找通過點擊事件從網址中移除參數。問題是該參數可能在其之前或之前有一個&。所以表格是search=MYSEARCHTERM&search=MYSEARCHTERM搜索並從網址中刪除可選字符的參數

我有以下似乎適用於一個或其他,但不是兩個都正常工作。我在想,我可以有一個if/else語句,其中之一包含這樣的內容。 (對不起蹩腳的正則表達式,但我以前從未編寫過它)

var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);

$('.searchKeyword').click(function() { 
    $(this).remove(); 
    var searchKeywordRegx = new RegExp('search=' + searchKeyword); 
    console.log(searchKeywordRegx); 
    document.location.href = String(document.location.href).replace(searchKeywordRegx , ""); 
}); 

我是大錯特錯嗎?

回答

2

使用?,使一些可選的正則表達式:

var searchKeywordRegx = new RegExp('&?search=' + searchKeyword); 
+0

啊!很簡單。謝謝 – LMG

1

看來你可以做到這一點沒有正則表達式。如果您只是刪除文檔位置的「搜索」部分:

document.location.search = document.location.search 
    .replace('search=' + encodeURI(searchKeyword), ''); 
+0

我聽說encodeURI,但我不熟悉它。我必須檢查一下。謝謝。 – LMG

+0

@LMG,我正在使用'encodeURI',因爲它可以確保值具有正確的編碼字符串。例如,如果字符串是'search = testing this'(帶空格),那麼URL中的內容是'search = testing%twentyis'。因此,'encodeURI'確保您傳遞給它的值將匹配它在URL中的外觀。 – KevBot

+0

感謝您的澄清。 – LMG

相關問題