I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value: www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
#page=(number)to#page=(number + 1)or how to capture some unspecified regexp pattern (the ampersands confuse me), or both (or something else). If you could clarify a bit more, it would be easier to assist.#page=(number)with number being the valuevar value = currentPage(current page being an int). This value can be any int, in the example it just so happens to go up by one. The regex is there to check if the url already contains#page=1(or#foo=bar&page=1which is the reason for the ampersand) so it updates the value instead of making it#page=1&page=2, which is where my current problem lies, I have it updating the hash overall but the regex isn't catching it so I am getting the latter.