0

I have an url like http://example.com/#var1=1 I'm adding new query params to the hash using this function:

function appendHash(name, val){
    var currentHash = location.hash;

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

However, this won't work as it should if the new name=val already exists in the current hash, e.g if current hash is #var1=1&var2=2 and I add var2=2 it will be appended again, and I don't want this to happen. What I need is to check if the new name and val already exist in the url and if exists skip it. Or maybe some other function will help?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Milen Mihalev
  • 350
  • 1
  • 7
  • 21
  • You may be interested in checking out http://jhash.codeplex.com – Chris Pietschmann Feb 16 '15 at 20:00
  • You might see if the answer to this [question](http://stackoverflow.com/questions/5245666/how-to-check-whether-a-given-string-is-already-present-in-an-array-or-list-in-ja) will help you. Look down into the last example they give. – joshmcode Feb 16 '15 at 20:04

1 Answers1

0

You can maybe use some regex for this :

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;
    }
}

You can even change the current value of one of your keys if needed by storing your matches in an object.

Or create a more dynamic hash checker with this regex.

Yoann
  • 3,020
  • 1
  • 24
  • 34