Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare URL with JavaScript

Tags:

javascript

I am trying to write a function like this:

if ( document.url!= 'search.php') {
    window.location = 'search.php' 
}

This is not working; it seems I may need to check if URL string contains 'search.php' - or is there another way I can do this check?

like image 674
TheLettuceMaster Avatar asked Sep 16 '25 22:09

TheLettuceMaster


1 Answers

It sounds like you're searching for indexOf. Note that it's not document.url, but document.URL:

if (document.URL.indexOf('search.php') == -1) {
    window.location = 'search.php';
}

Note: This will also match the following:

http://www.domain.com/search.php
http://www.domain.com/index.php?page=search.php&test
http://www.domain.com/search.php/non-search.php
http://www.domain.com/non-search.php#search.php

Extra note: Why are you doing this? If people have javascript disabled, they will never get forwarded. Maybe you're searching for the 301 or 302 header?

like image 175
h2ooooooo Avatar answered Sep 19 '25 14:09

h2ooooooo