Home > other >  Check if subdomain is true or false? javascript
Check if subdomain is true or false? javascript

Time:10-02

Newbie here and I've been trying to write a function that checks if a subdomain is true or false

any guidance is appreciated! and sorry if it's really basic

function test(t) {
  if (window.location.hostname === 'news.google.com') {
    return true;
  }
  return t;
}
let x;
console.log(test(x));

CodePudding user response:

So there are 2 ways you could go about this. From your example code we can remove the parameter as it isn't used, t in your example is always undefined. We can also just return the result of the equality operator since it will return true / false.

  1. If you want to have a static check i.e. always check for the same domain name
function test() {
  return window.location.hostname === 'news.google.com'
}
console.log(test());
  1. If you want to allow the domain name to change
function test(domain) {
  return window.location.hostname === domain
}
console.log(test('news.google.com'));

Note:

Naming functions is a very important concept so you might want to think of a name that better represents the operation taking place such as isDomainEqualTo(domain)

CodePudding user response:

It's kinda hard question, cuz you ain't saying true or false relatively to what. What is the kind of problem are you trying to solve?

If you want to check is it generally expected site you're on, then this is right. The page and its path you ain't be on, you'll be able to get its hostname and then make your steps. So...

More you can read here: https://www.w3schools.com/js/js_window_location.asp

And here's a lot of information about JS too: https://developer.mozilla.org/en-US/docs/Web/API/Location

  • Related