Javascript jQuery将查询参数附加到当前散列,忽略重复项
我有一个像http://example.com/var1=1 我正在使用以下函数向哈希添加新的查询参数:Javascript jQuery将查询参数附加到当前散列,忽略重复项,javascript,jquery,hash,hashmap,Javascript,Jquery,Hash,Hashmap,我有一个像http://example.com/var1=1 我正在使用以下函数向哈希添加新的查询参数: function appendHash(name, val){ var currentHash = location.hash; if(!currentHash){ location.hash = '#'+name+'='+val; }else{ location.hash = currentHash+'&'+name+'
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,那么它将再次追加,我不希望发生这种情况。
我需要的是检查url中是否已经存在新名称和val,如果存在则跳过它。或者其他函数会有所帮助?您可以使用一些正则表达式:
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;
}
}
如果需要,您甚至可以通过将匹配项存储在对象中来更改其中一个键的当前值
或者用这个正则表达式创建一个更具动态性的哈希检查器。您可能有兴趣签出它,您可以看看这个问题的答案是否对您有帮助。看看他们给出的最后一个例子。