简体   繁体   中英

Is there any way to fetch only Subdomain from URL in Angular 8?

Below is my URL and I want only subdomain ie dnyaneshtechno

Url : https://dnyaneshtechno.sharepoint.com

As per above URL I want to fetch only 'dnyaneshtechno' I am using angular 8 for front end so Can someone please help me on this.

You can use split and substr functions or get subdomain from an url

Example :

Dynamic link :

let getLink =  window.location.href ; 
console.log(getLink)          // dynamic link 
var  subdomain = getLink.substr(COUNT, 1000).split(".")[0]

Using Split Method :

var Link = "https://SUBDOMAIN.DOMAIN.com"
var subdomain = Link.substr(COUNT, 1000).split(".")[0]
console.log(subdomain)      //SUBDOMAIN

Or Using get subdomain form link

const { hostname }  = new URL('https://SUBDOMAIN.DOMAIN.com')
const [subdomain] = hostname.split('.')
console.log(subdomain)    //SUBDOMAIN

i hope i will be helpful fo all !

Assuming you want to extract the subdomain from the string, this isn't an Angular problem, but pure JavaScript. There's the URL constructor that can do this:

 const { hostname } = new URL('https://dnyaneshtechno.sharepoint.com') const [subdomain] = hostname.split('.') console.log(subdomain)

You can use substr and split functions, ie.

var a = "https://dnyaneshtechno.sharepoint.com"
var subdomain = a.substr(9, 1000).split(".")[0]

For an angular based solution by injecting the DOCUMENT from @angular/platform-browser like this

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class SampleService {

    constructor(@Inject(DOCUMENT) private document: Document) {
    }

    getDomainname() : string{
        return this.document.location.host.split('.')[0];
    }
}

getDomainName() will return the domain of current page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM