jQuery将查询参数附加到当前哈希中,忽略重复项

jQuery append query parameters to current hash omitting duplicates

本文关键字:哈希中 查询 参数 jQuery      更新时间:2023-11-25

我有一个类似http://example.com/#var1=1的url我使用以下函数将新的查询参数添加到哈希中:

function appendHash(name, val){
    var currentHash = location.hash;
    if(!currentHash){
         location.hash = '#'+name+'='+val;
    }else{
         location.hash = currentHash+'&'+name+'='+val;
    }
};

然而,如果新的name=val已经存在于当前哈希中,这将无法正常工作,例如,如果当前哈希是#var1=1&var2=2,并且我添加了var2=2,它将再次被附加,我不希望发生这种情况。我需要的是检查新名称和val是否已经存在于url中,如果存在,请跳过它。或者其他功能可能会有所帮助?

您可以为此使用一些正则表达式:

function appendHash (name, val) {
    var currentHash = location.hash;
    var regex = /(?:[#&])([^=]+)=([^&]+)/g;
    var found = false;
    st.replace(regex, function (part, key, value) {
        if (key === name && value === val) {
            found = true;
        }
    });
    if (!currentHash) {
        location.hash = '#' + name + '=' + val;
    } else if (!found) {
        location.hash = currentHash+'&'+name+'='+val;
    }
}

如果需要,您甚至可以通过将匹配项存储在对象中来更改某个键的当前值。

或者用这个正则表达式创建一个更动态的哈希检查器。