javascripthttp-redirectanchor

Javascript to redirect from #anchor to a separate page


I have a set of links with #anchors pointing to a single webpage and I would like to smoothly move to a model with a separate webpage for each of those links. I want the old links to keep working using a redirect.

Old link style:

/all_products#A
/all_products#B
/all_products#C

New link style:

/products/A
/products/B
/products/C

I know that the server does not receive the #anchor name in the request but Javascript might.

Is it possible to automatically redirect from /all_products#A to /products/A using Javascript?

JQuery would be fine, it's being used on the site anyway.


Solution

  • I hope this can help :)

    var urlSplit = document.URL.split("#");
    if (urlSplit[1]) {
        location.href = "http://www.example.org" + "/" + urlSplit[1];
    }
    else {
        location.href = "http://www.example.org";
    }