如果窗口.位置以HTML结束,执行javascript

If window.location ends with html execute javascript

本文关键字:执行 javascript 结束 HTML 窗口 位置 如果      更新时间:2023-09-26

如果当前位置包含html,则执行javascript。我试过下面的,但它不工作

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
}
var isHTML = "html" === window.location.pathname.split(".").pop().toLowerCase();
if ( isHTML ) {
    //execute javascript here
}

参见Amaan answer using regexp:

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

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
}
演示

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
}

我的建议:

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

如果值只需要一次,就不必声明局部变量…

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")
}