i use the following to take a URL e.g. domain.com/#2 and then i use that fragment to redirect the users to domain.com/?page=2.
However, sometimes the user may be shown just a single hash and no number or i might use a keyword in the URL when clicking a form e.g. /#feedback.
The problem is this causes an issue with the code i use. How can i modify the provided code in a way that will only act upon the URL if its how i want the URL to be.
One way is to check if the fragment value is 'feedback' for example, but i would like to catch a way for a user perhaps entering a value or an odd form just creating a blank fragment value.
If the URL doesnt contain a #(then a number) or a given page id then dont do anything.
So the URL of:
domain.com/#2
Will redirect to:
domain.com/?page=2
Or if the URL already has a ?page=(number) it will add the fragment value to the number so:
domain.com/?page=2#2
Will direct to:
domain.com/?page=4
My initial thought it checking if the fragment is numeric, otherwise treat it as a 0.
So this:
/*
Check if the URL has a # value. When a user visits a page from another / reloads the page and
it has a # fragment included, this code converts the # value and redirects the user to a page
such as domain.php?page=THE FRAGMENT VALUE
If the URL already contains a page value, it adds that value to the hash value and will
redirect the user to the new value page.
*/
// First get the page URL and split it via # and ? signs
var parts = location.href.split('#');
var queryParameters = location.search.split('?');
// Now we get the value of the page value in the URL if there is one
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
// Next we check how many parts there are in the URL and if this a value, we add it to the current page
// and redirect to that new page number
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '?';
}
var newPageNumber = parseInt(parts[1], 10) + parseInt(pageNumber, 10);
location.href = mark + 'page=' + newPageNumber;
}