Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

If window.location ends with html execute javascript

Execute javascript if current location contains html in in. I have tried the below but it doesn't work

var winloc = window.location; //for e.g http://mysite.com/home.html
var ishtml = winloc.match(/html/$);
var dothtml = "html";
if(dothtml==ishtml){
//execute javascript here
}

Upvotes: 0

Views: 1600

Answers (5)

Andreas Louv
Andreas Louv

Reputation: 47099

var isHTML = "html" === window.location.pathname.split(".").pop().toLowerCase();
if ( isHTML ) {
    //execute javascript here
}

See Amaan answer using regexp:

https://stackoverflow.com/a/8619635/887539

Upvotes: 3

Some Guy
Some Guy

Reputation: 16190

var winloc = window.location.pathname; //for e.g http://mysite.com/home.html
var ishtml = /html$/i.test(winloc); //Remove the i if you want to match only html and not HTML
if(ishtml === true){
    //Your JS
}

Demo

Upvotes: 1

mplungjan
mplungjan

Reputation: 177692

var re = /.*(\.html)$/i;
var winloc = window.location.href; //for e.g http://mysite.com/home.html
var ishtml = winloc.match(re)[1];
var dothtml = ".html";
if(dothtml==ishtml){
//execute javascript here
 alert("yes")
}

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185883

My suggestion:

if ( window.location.pathname.match( /html$/ ) ) {
    // do it
}

You don't have to declare local variables if the value are only needed once...

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148524

var winloc = window.location; //for e.g http://mysite.com/home.html
var ishtml = winloc.match(/html$/i);
var dothtml = "html";
if(dothtml==ishtml){
//execute javascript here
}

Upvotes: 0

Related Questions