Reputation: 1167
Ok so I have a series of urls ranging from something like
http://www.test.com/sasa
http://www.test.com/sasdassasdssda
http://www.test.com/ewewewewsasa
http://www.test.com
What I want to do is just take a substring of each url which goes from the start to the third / and if there is no third / take the original string
basically I want to know how to get the position of the third /, as I assume if there is no third / then it will be -1 so I can just grab the position and if its not -1 do the substring bit. Anyway enough of me rambling. How do I find the position of the third slash?
Upvotes: 1
Views: 293
Reputation: 174700
It sounds like you want the URI without the path (the segment after the third /
) and the trailing /
itself.
The easiest way to do that, is simply to convert the string to an actual URI object and then use the AbsoluteUri
and PathAndQuery
properties to calculate where to make to incision:
function Get-UriSchemeAndAuthority
{
param(
[string]$InputString
)
$Uri = $InputString -as [uri]
if($Uri){
$FullUri = $Uri.AbsoluteUri
$Path = $Uri.PathAndQuery
$SlashIndex = $FullUri.Length - $Path.Length
return $FullUri.Substring(0,$SlashIndex)
} else {
throw "Malformed URI"
}
}
Works with all of your test cases:
PS C:\> Get-UriSchemeAndAuthority http://www.test.com/sasa
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com/sasdassasdssda
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com/ewewewewsasa
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com
http://www.test.com
Alternatively, take the Scheme
and Authority
properties and create a new string from those (makes it much more concise) :
function Get-UriSchemeAndAuthority
{
param(
[string]$InputString
)
$Uri = $InputString -as [uri]
if($Uri){
return $("{0}://{1}" -f $Uri.Scheme,$Uri.Authority)
} else {
throw "Malformed URI"
}
}
Upvotes: 2