0

How can I add something in JavaScript that will check the web site URL of someone on a web site and then redirect to a certain page on the web site, if a match is found? For example...

The string we want to check for, will be mydirectory, so if someone went to example.com/mydirectory/anyfile.php or even example.com/mydirectory/index.php, JavaScript would then redirect their page / url to example.com/index.php because it has mydirectory in the url, otherwise if no match is found, don't redirect, I'm using the code below:

var search2 = 'mydirectory';
var redirect2 = 'http://example.com/index.php'

if (document.URL.substr(search2) !== -1)
    document.location = redirect2

The problem with that, is that it always redirects for me even though there is no match found, does anyone know what's going wrong and is there a faster / better way of doing this?

1
  • 1
    why would you be doing this? if i had my JS off, i can still view the pages under mydirectory. better look into better solutions like .htaccess and routing Commented Apr 11, 2012 at 3:08

2 Answers 2

2

Use String.indexOf() instead:

if (window.location.pathname.indexOf('searchTerm') !== -1) {
    // a match was found, redirect to your new url
    window.location.href = newUrl;
}
Sign up to request clarification or add additional context in comments.

3 Comments

pathname is better than href, using href means this will cause a redirect: http://www.example.com/foo.php?someParameter=mydirectory
Using the href can mean false positives, like my example in the above comment.
@MattGreer oh i see, they can have the search term in the querystring to generate a false positive. i will update my answer.
0

substr is not what you need in this situation, it extracts substrings out of a string. Instead use indexOf:

if(window.location.pathname.indexOf(search2) !== -1) {
    window.location = redirect2;
}

If possible it's better to do this redirect on the server side. It will always work, be more search engine friendly and faster. If your users have JavaScript disabled, they won't get redirected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.