I am trying to extract just the websites name from a URL and all the stackoverflow answers haven't led me anywhere.
My URL is in the following format:
https://order-dev.companyname.com
I just want to extract order-dev
from the URL.
I am trying to extract just the websites name from a URL and all the stackoverflow answers haven't led me anywhere.
My URL is in the following format:
https://order-dev.companyname.com
I just want to extract order-dev
from the URL.
If you have an express framework with your node app then it is easy to get a domain/list of subdomains directly from the incoming request..
Using Express Framework
req.hostname() // returns 'example.com'
req.subdomains() // return ['ferrets', 'tobi'] from Host: "tobi.ferrets.example.com"
For plain NodeJS
All Incoming request will contain the following header origin
which can be extracted using the following request.headers.origin
in any functions where you handle your incoming request MDN LINK
In most JavaScript engines (i.e., most browsers (excluding IE) and Node) you can also use URL
for this, specifically URL.host
combined with String.prototype.split()
:
const siteUrl = 'https://order-dev.companyname.com';
const myURLObject = new URL(siteUrl);
const subdomain = myURLObject.host.split(".")[0];
console.log(subdomain); // "order-dev"