Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check If Subdomain Exist

I wanted to check if demo exist in my URL.

So if my url is either https://demo.stackoverflow.com/ or https://demo.stacks.com/ or https://demo.hello.com/, it will all return true.
if it is just https://stackoverflow.com/ without the word demo, it will return false.

So how will I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Current Code

  <script>
  if (window.location.hostname === 'https://demo.stackoverflow.com/') {
    document.write('<script src="./script.min.js"></' + 'script>');
  } 
  </script>

>Solution :

The URL API has pretty good support, browser-wise. Use it to parse the subdomain(s) from window.location and check if demo is present at any point in the hostname:

function demoSubdomainIsPresent(url) {
  var domains = new URL(url).hostname.split(".");
  return domains.includes("demo");
}

// Should return true:
console.log(demoSubdomainIsPresent('https://demo.example.com'));
console.log(demoSubdomainIsPresent('https://east.demo.example.com'));

// Should return false:
console.log(demoSubdomainIsPresent(window.location)); // window.location for snippets is 'stacksnippets.net', should return false
console.log(demoSubdomainIsPresent('https://example.com'));
console.log(demoSubdomainIsPresent('https://example.com/demo.php'));
console.log(demoSubdomainIsPresent('https://exmaple.com/page.php?q=demo'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading