check certain url in javascript?

Go To StackoverFlow.com

0

how can i add something in javascript that will check the website url of someone on a website and then redirect to a certain page on the website, if a match is found? for example...

the string we want to check for, will be mydirectory, so if someone went to mysite.com/mydirectory/anyfile.php or even mysite.com/mydirectory/index.php javascript would then redirect their page / url to mysite.com/index.php because it has mydirectory in the url, how can i do that using javascript?

2012-04-05 00:09
by codrgi


0

If I have understood the question correctly, then it is fairly simple and can be achieved using document.URL

var search = 'mydirectory'; // The string to search for in the URL.
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found
if(document.URL.substr(search) !== -1) { // If the location of 
    // the current URL string is any other than -1 (doesn't exist)
    document.location = redirect // Redirect the user to the redirect URL.
}

Using document.URL you can check anything in the URL, however you might want to look into using something like Apache's mod_rewrite for redirecting the user before they even load the page.

2012-04-05 00:22
by Dan Prince
You have an extra = in your if condition - neo108 2012-04-05 00:27
It's better style to use exactly equals (=== and !==) to avoid problems such as (0 == false) or (-1 == '-1') returning true. It doesn't affect this situation, but it doesn't hurt either. http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-us - Dan Prince 2012-04-05 00:35
Thanks @DanPrince for that. I learnt something new - neo108 2012-04-05 00:44


0

Check out window.location, particularly it's properties and methods. You would be interested in (part of the) pathname property (you can split it on /) and the href property to change the page.

This is all assuming the javascript is being served in the first place; so I'm assuming anyfile.php and index.php would all result in the JS being served and not some 'generic 404' message.

2012-04-05 00:19
by RobIII
Ads