Joseph
Joseph

Reputation: 7755

Check if subdomain exists

I want to check if the subdomain demo exists in my URL.

So if my URL is either https://demo.stackoverflow.com/ or https://demo.stacks.com/ or https://demo.hello.com/, the function should return true.

If the URL is just https://stackoverflow.com/, without the word demo, the function should return false.

So how can I do that?

Current Code

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

Upvotes: 2

Views: 551

Answers (2)

esqew
esqew

Reputation: 44698

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'));

Upvotes: 1

Tim
Tim

Reputation: 162

You can use the startsWith method.

window.location.host.startsWith('demo.')

This will only work for checking if that is the subdomain though.

Edit: It shouldn't matter if you use host or hostname if you are just checking for a subdomain.

Upvotes: 1

Related Questions