Home > front end >  Extract first part of URL
Extract first part of URL

Time:01-18

I have an URL like so:

https://www.example.com/oauth/connect/token

I want to get only https://www.example.com and I have tried a bunch of ways to get this but all the ways I have tried require me to hardcode multiple /s.

Example:

$Url.Split('/')[0] "//" $url.split('/')[2]

Is there a way to do this without using the harcoding?

CodePudding user response:

You may use [System.Uri], to 'cast' the string into an System.Uri class.

$url = [System.Uri]"https://www.example.com/oauth/connect/token"

You can then use the host and scheme to get the part of the URL you want.

$result = $url.Scheme, $url.Host -join "://"

You could also remove the AbsolutePath from the entire URL.

$url = [System.Uri]"https://www.example.com/oauth/connect/token"

$result = $url.AbsoluteUri.Replace($url.AbsolutePath, "")

This is the complete list of attributes that the System.Uri instance will have:

AbsolutePath   : /oauth/connect/token
AbsoluteUri    : https://www.example.com/oauth/connect/token
LocalPath      : /oauth/connect/token
Authority      : www.example.com
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /oauth/connect/token
Segments       : {/, oauth/, connect/, token}
IsUnc          : False
Host           : www.example.com
Port           : 443
Query          :
Fragment       :
Scheme         : https
OriginalString : https://www.example.com/oauth/connect/token
DnsSafeHost    : www.example.com
IdnHost        : www.example.com
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :
  • Related