简体   繁体   中英

Get current URL but excluding some parts

The current URL looks like: http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA

I need to get the part before the #, so it's gonna be: http://mycompany.com/jobs/java-developer.aspx

How can I do that in code behind?

You can use Uri class:

var uri = new Uri("http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA");
var result = uri.GetLeftPart(UriPartial.Path);
string url = "http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA";
string path = url.Substring(0, url.IndexOf("#"));
Uri myUri = new Uri("http://mycompany.com/jobs/java-developer.aspx#.U9-RH2OTLfA");
string url = myUri.Host + myUri.LocalPath;

you can create uri with string then get the parts

    private String getGoodString(String url)
    {
         return url.Substring(0, url.IndexOf("#") - 1);
    }

This will return everything up to but not including the # symbol in your string. Assuming you have a # to signal when to stop getting the string of the URL. Otherwise if there are multiple #. You can use lastIndexOf , or firstIndexOf if you need to "trim the fat".

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