Athanatos
Athanatos

Reputation: 1089

Javascript window.location.href comparison with index.php or root name

I would like to run a specific piece of code in JS when

1)The page is mysite.com/index.php or 2) when index is not present e.g mysite.com . (You can do that using apache )

For 1 I am using 1)if ( /index\.php$/.test(window.location.href)) { //code here }

How can I do it for both ?

2)I have tried

if ( /http:\/\/mysite\.com/g.test(window.location.href))
{
}

But this works for every url (e.g mysite.com/anythinghere.php)

Upvotes: 0

Views: 1417

Answers (2)

Stphane
Stphane

Reputation: 3456

You could try this if you want know you loaded the home page

 if(/\/(index\.php)?$/.test(window.location.pathname)){
        // ...
    }

Upvotes: 1

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

You can check this more easily by comparing window.location.pathname value.

if (window.location.pathname == '/' || window.location.pathname == '/index.php') {
    // code here
}

Upvotes: 1

Related Questions