2010-09-20 48 views
8

我們'http://site.com/movies/moviename/'頁面jQuery的檢查當前的URL

我們怎麼能知道,有沒有/movies/在當前的URL(後直接網站的根目錄)?


代碼應該給:

真正的'http://site.com/movies/moviename/'

和虛假的'http://site.com/person/brad-pitt/movies/'


感謝。

回答

12

你可以嘗試String對象的indexOf方法:

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

在jQuery中沒有任何東西可以用於這個,這是純Javascript。

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

基本字符串操作...

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

請解釋'str'和'path'是什麼。 – James 2010-09-20 16:47:07

+0

它可以採取當前網址本身? – James 2010-09-20 16:48:23

+0

其實我正在尋找一些'true:false'解決方案 – James 2010-09-20 16:48:58