2010-09-20 30 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