2017-02-07 11 views
0

提出されたURLを確認しようとしています(追加パスは除く)。if/elseステートメントのURLを確認していますか?

ユーザーが投稿したURLは次のとおりです。次に、ユーザは'http://stackoverflow.com/questions/ask'を提出

var inputUrl = document.getElementById("inputVal").value; 

場合、私は関係なく、'http/https'の、サイトは「stackoverflow.com」であるかどうかを判断しますのif/else文を作成しようとしていますまたは任意の'/.../.../'.com

if (inputUrl == "stackoverflow.com") { 
console.log ("stackoverflow"); 
} else { 
console.log("not stackoverflow"); 
} 

後に任意の助けいただければ幸いです。

+0

質問/問題がありますか? – Andreas

+0

'' http://stackoverflow.com/questions/ask '!=' stackoverflow.com ''。 '=='は完全な文字列を部分文字列ではなく完全文字列と比較します。 – Barmar

+0

正確に。私は変数*、つまり* stackoverflow.com *を置き換えるために*を使うことができるトリックを覚えていると思いましたが、それはうまくいかないようです。 – Jack

答えて

0
if(inputUrl.toLowerCase().indexOf("stackoverflow.com") > -1) { 
     ... 
    } 
+0

それは完璧に働いた、ありがとう! – Jack

1

ブラウザは、あなたが(MDNで見つけることができる)のため、ほとんどのものを行う持っている小さなトリック:

var url = document.createElement('a'); 
url.href = 'http://stackoverflow.com/questions/ask'; 
console.log(url.host);  // stackoverflow.com 


if (url.host == "stackoverflow.com") { 
    console.log ("stackoverflow"); 
} else { 
    console.log("not stackoverflow"); 
} 

あなたは、プロトコルまたはハッシュのようなURLの他の部分にもアクセスすることができます同じように。

+0

素晴らしいです、ありがとうございます。それはうまくいくが、1つの小さな問題があるようだ。 'url.host'は' stackoverflow.com'ではなく 'www.stackoverflow.com'として出ています。これにより、いくつかのシナリオで問題が発生します。どのようにして 'www.'を削除できるのか分かりますか? – Jack

+0

@Jackサブドメインは完全に異なるサイトを指し示すことができるので、ホストの一部です。その時点で、String操作を使用する必要があります。 – Sirko

1

$("button").on("click",function(){ 
 
var inputUrl = document.getElementById("inputVal").value; 
 
    inputUrl=inputUrl.split("http://")[1] || inputUrl.split("https://")[1] ; 
 
    inputUrl=inputUrl.split("/")[0]; 
 
    if (inputUrl == "stackoverflow.com") { 
 
     console.log ("stackoverflow"); 
 
     } else { 
 
     console.log("not stackoverflow"); 
 
     } 
 

 
}) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<input id="inputVal" value="http://stackoverflow.com/questions/ask"> 
 
<button> 
 
submit 
 
</button>

jsfiddleデモ:https://jsfiddle.net/geogeorge/h40dvbq6/2/

関連する問題