12

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.

5 Answers 5

15

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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'));

7 Comments

please explain what is 'str' and 'path'.
can it take current url itself?
actually I'm searcing for some 'true : false' solution
@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/"
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.
|
2

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

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

Comments

1

You should look at the jQuery-URL-Parser -

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

Comments

0

You can split the URL in some parts and decide what to do:

    var url = $(location).attr('href');
    parts = url.split("/");
    part_one = parts[parts.length-1];
    part_two = parts[parts.length-2];
    if(part_two == 'movies') {
     //do something
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.