Javascript to redirect C # anchor to a separate page

I have a set of C # anchors links pointing to one web page, and I would like to smoothly switch to a model with a separate web page for each of these links. I want the old links to continue to work using redirects.

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 get the name #anchor in the request, but Javascript can.

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

JQuery will be fine, it is still used on the site.

+5
source share
5 answers

Hope this helps :)

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

, URL- .

// Closure-wrapped for security.
(function () {
    var anchorMap = {
            "A": "/products/A"
            "B": "/products/B"
            "C": "/products/C"
    }
    /*
    * Best practice for extracting hashes:
    * /questions/44892/how-to-get-the-anchor-from-the-url-using-jquery/321011#321011
    */
    var hash = window.location.hash.substring(1);
    if (hash) {
        /*
        * Best practice for javascript redirects: 
        * /questions/10/how-to-redirect-to-another-webpage-in-javascriptjquery/322#322
        */
        window.location.replace(anchorMap[hash]);
    }
})();
+8

HTML <head>, , :

<script>
function checkURL() {
    var old_path = '/all_products';
    if (window.location.pathname != old_path) {
        // Not on an old-style URL
        return false;
    }
    // Some browsers include the hash character in the anchor, strip it out
    var product = window.location.hash.replace(/^#(.*)/, '$1');
    // Redirect to the new-style URL
    var new_path = '/products';
    window.location = new_path + '/' + product;
}
checkURL();
</script>

URL , .

window.location, URL, .

script .

+2

jquery href :

$('a').each(function() {
  this.href = this.href.replace(/all_products#/, 'products/');
});

:

$('a').click(function() {
  window.location = this.href.replace(/all_products#/, 'products/');
  return false;
});
+1

:

<a href="/all_products#A" onclick="return redirectMe(this);">A</a>
<a href="/all_products#B" onclick="return redirectMe(this);">B</a>
<a href="/all_products#C" onclick="return redirectMe(this);">C</a>
<a href="/all_products#D" onclick="return redirectMe(this);">D</a>
<a href="/all_products#E" onclick="return redirectMe(this);">E</a>

<script type="text/javascript">
function redirectMe(a){
   var aa=a+"";
   window.location=aa.replace(/#/g,"/");
}
</script>   
0
source

All Articles