2011-12-23 3 views
0

はJavaScriptを実行実行します。私は以下試してみましたが、それは使用してwindow.locationのは、HTMLで終わる場合、現在の場所が中に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 
} 
+4

使用 'location.pathname'。 'index.php?type = .html'(クエリ文字列)か' foo#hi.html'(ハッシュ)と一致させたくありません。 –

答えて

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

参照Amaanの答えを動作しません。正規表現:

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

+0

+1。私はあなたの方法が気に入っていますが、この場合、正規表現を使う方が速くなると思います。 –

+0

path-nameにドットがないと、これが壊れます。 –

+0

ちょうど私がJSPerfテストをすると思っていました。正規表現は私にとってより速かった。 http://jsperf.com/pop-vs-regexp –

0
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 
} 
1
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

+0

大文字小文字を区別しない '/html$/i.test(winloc)'を追加したい場合があります。 – andlrc

+0

すでに完了しています。 :) –

0

私の提案:

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

値は一度しか必要とされている場合は、ローカル変数を宣言する必要はありません...

0
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") 
} 
関連する問題