0

How can I add something in JavaScript that will check the website URL of someone on a web site 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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
codrgi
  • 211
  • 1
  • 4
  • 10

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
  • 8,488
  • 2
  • 43
  • 93
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
  • 29,491
  • 13
  • 89
  • 120
  • 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