tags:

views:

35

answers:

4

We are on page 'http://site.com/movies/moviename/'

How can we know, is there /movies/ in current url (directly after site's root)?


Code should give:

True for 'http://site.com/movies/moviename/'

And false for 'http://site.com/person/brad-pitt/movies/'


Thanks.

+1  A: 

There is nothing in jQuery that you use for that, this is plain Javascript.

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

Basic 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'));
Josh Stodola
please explain what is 'str' and 'path'.
Happy
can it take current url itself?
Happy
actually I'm searcing for some 'true : false' solution
Happy
@Happy This is a true/false solution. What are you talking about? The function returns true or false depending on whether or not the URL passed in has the given path after ".com/"
Josh Stodola
In this solution, str is the URL, and path is what you want to search for (movies). It will return true if movies is directly after the site root, false otherwise. It will work, but is slightly more convoluted than other solutions given.
JungleFreak
@JungleFreak Slightly convoluted, yes, but it is the most flexible. And, how convoluted can it be... we're talking about two substrings here.
Josh Stodola
@Josh Stodola: That's why I said just "slightly more convoluted" and voted it up. :)
JungleFreak
+3  A: 

You can try the String object's indexOf method:

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

You should look at the jQuery-URL-Parser -

http://github.com/allmarkedup/jQuery-URL-Parser

Kris Krause