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?

codrgi
  • 187
  • 1
  • 3
  • 9

2 Answers2

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.

RobIII
  • 7,931
  • 1
  • 37
  • 85
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.

Dan Prince
  • 28,326
  • 12
  • 86
  • 115
  • You have an extra `=` in your if condition. – neo108 Apr 05 '12 at 00:27
  • 1
    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-use – Dan Prince Apr 05 '12 at 00:35