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