Maulik Lathiya
Maulik Lathiya

Reputation: 173

redirect using js if window location is 1.html

i am lookingfor js which works like if is on a.html then

window.location="http://www.a.com/1"

else if on page b.html then

window.location="http://www.a.com/2"

Upvotes: 0

Views: 598

Answers (1)

Elie
Elie

Reputation: 76

You will have to first check your current location through window.location.href to get the url. Then use substr(string, begin, lenght (optional) ) to trunc your url to the end

//Address of your website
var url="http://example.com/"

function foo(){
    var path=substr(window.location.href,url.length);
    switch(path){
        case "a.html": window.location="http://www.example.com/1"; break;

        case "b.html": window.location="http://www.example.com/2"; break;

    }
}
//don't forget to call your function

But this wouldn't work if you have internal likes such as http://example.com/a.html#about-us for example

Here is how to handle it

//Address of your website
var url="http://example.com/"

function foo(){
    var path=substr(window.location.href,url.length).substring(0, window.location.href.indexOf('#'));
    switch(path){
        case "a.html": window.location="http://www.example.com/1"; break;

        case "b.html": window.location="http://www.example.com/2"; break;

    }
}
//don't forget to call your function

For more information

substr() http://www.w3schools.com/jsref/jsref_substr.asp

about Substring https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/substring and

Upvotes: 1

Related Questions