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?

2
  • You may be interested in checking out jhash.codeplex.com Commented Feb 16, 2015 at 20:00
  • You might see if the answer to this question will help you. Look down into the last example they give. Commented Feb 16, 2015 at 20:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.