2010-09-20 20 views
8

Wir sind auf Seite 'http://site.com/movies/moviename/'jQuery Check aktuelle URL

Wie können wir wissen, gibt es /movies/ in aktueller URL (direkt nach der Wurzel der Site)?


-Code geben sollte:

Wahre für 'http://site.com/movies/moviename/'

Und false für 'http://site.com/person/brad-pitt/movies/'


Dank.

Antwort

12

Sie das StringindexOf Methode des Objekts versuchen:

var url = window.location.href; 
var host = window.location.host; 
if(url.indexOf('http://' + host + '/movies') != -1) { 
    //match 
} 
2

Es gibt nichts in jQuery, das Sie für das verwenden, das ist Javascript.

if (/\/\/[^\/]+\/movies\//.test(window.location.href)) { 
    // inside the movies folder 
} 
2

Grund String-Manipulation ...

function isValidPath(str, path) { 
    str = str.substring(str.indexOf('://') + 3); 
    str = str.substring(str.indexOf('/') + 1); 
    return (str.indexOf(path) == 0); 
} 

var url = 'http://site.com/movies/moviename/'; // Use location.href for current 
alert(isValidPath(url, 'movies')); 

url = 'http://site.com/person/brad-pitt/movies/'; 
alert(isValidPath(url, 'movies')); 
+0

Bitte erläutern Sie, was 'str' und 'Pfad' ist. – James

+0

kann es aktuelle URL selbst nehmen? – James

+0

tatsächlich suche ich nach einer 'wahr: falsch' Lösung – James