Alex
Alex

Reputation: 11

How do I add a statement in javascript based on the current url?

Basically I want to check what url the user is on and compare it to a default value and then run a statement

Let's say my url is https://stackoverflow.com/questions/ask, I'm trying to do this, and it's not working:

<script type="text/javascript">
      if(document.location.href('/questions/ask') > 0)
  {
    [do this];
  }

Thanks for the help(noob question I know)

Upvotes: 1

Views: 120

Answers (3)

seanmonstar
seanmonstar

Reputation: 11444

window.location.href gives you the whole url. You can also access other properties of location, like protocol, pathname, hash, host.

if(window.location.pathname == '/questions/ask')

Upvotes: 0

Andrei Serdeliuc ॐ
Andrei Serdeliuc ॐ

Reputation: 5878

Try this:

var loc = new String(window.location);
if(loc.match('/questions/ask')) {
    // do something here
}

Upvotes: 0

Bob
Bob

Reputation: 99794

Give this a try, you are missing the indexOf method.

if(document.location.href.indexOf('/questions/ask') > -1)

But I believe you should be going off of the window object, I think document is deprecated (but still works).

if(window.location.href.indexOf('/questions/ask') > -1)

You also want to check to see if the index is greater than negative one because zero is technically a correct position.

Upvotes: 1

Related Questions