Jack
Jack

Reputation: 23

Checking a URL in an if/else statement?

I'm trying to check a submitted URL (excluding any additional paths).

The user submitted URL is:

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

If the user submits 'http://stackoverflow.com/questions/ask' then I'm trying to create an if/else statement that will determine whether the site is 'stackoverflow.com', regardless of 'http/https' or any '/.../.../' after .com

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

Any help would be greatly appreciated.

Upvotes: 0

Views: 5813

Answers (3)

Geo George
Geo George

Reputation: 359

$("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 Demo : https://jsfiddle.net/geogeorge/h40dvbq6/2/

Upvotes: 1

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6684

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

Upvotes: 1

Sirko
Sirko

Reputation: 74086

A little trick to have the browser do most stuff for you (can be found at 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");
}

The same way you can also access other parts of the URL like protocol or hash.

Upvotes: 1

Related Questions