Home > Software engineering >  C# - Delete the slash at the end of URI
C# - Delete the slash at the end of URI

Time:11-03

I would like to remove the slash at the end of the URI, while keeping the query parameter.

For example:

I get an object of type URI as input with the value: https://stackoverflow.com/questions/ask/

I would like to remove the last "/" to get: https://stackoverflow.com/questions/ask


In some cases I may have parameters: https://stackoverflow.com/questions/ask/?test=test1

I would like to get: https://stackoverflow.com/questions/ask?test=test1

Thanks in advance.

CodePudding user response:

string url1 = "https://stackoverflow.com/questions/ask/";
string url2 = "https://stackoverflow.com/questions/ask/?test=test1";

//remove slash at end
Console.WriteLine(url1.TrimEnd('/'));

//remove slash preceding query parameters
int last = url2.LastIndexOf('?');
url2 = url2.Remove(last - 1, 1);
Console.WriteLine(url2);

There probably is a way to search and replace the last slash using Regex as well, since there is Regex.Replace()

CodePudding user response:

You can first check if the URL has any query parameters by checking latest index of ? character. If there is ?, take before that, remove last character (which is / that you don't want) and combine it again. If it doesn't have any query parameters, just remove the last character! You can create an extension method like this;

public static string RemoveSlash(this string url)
{
    var queryIndex = url.LastIndexOf('?');
    if (queryIndex >= 0)
    {
        var urlWithoutQueryParameters = url[..queryIndex];
        if (urlWithoutQueryParameters.EndsWith("/"))
        {
            urlWithoutQueryParameters = urlWithoutQueryParameters[..^1];
        }
        var queryParemeters = url[queryIndex..];

        return urlWithoutQueryParameters   queryParemeters;
    }
    else if (url.EndsWith("/"))
    {
        return url[..^1];
    }
    
    return url;
}

Then you can use it like this;

var url1 = "https://stackoverflow.com/questions/ask";
var url2 = "https://stackoverflow.com/questions/ask/";
Console.WriteLine(url1.RemoveSlash()); // https://stackoverflow.com/questions/ask
Console.WriteLine(url2.RemoveSlash()); // https://stackoverflow.com/questions/ask

var url3 = "https://stackoverflow.com/questions/ask/?test=test1";
var url4 = "https://stackoverflow.com/questions/ask?test=test1";
Console.WriteLine(url3.RemoveSlash()); // https://stackoverflow.com/questions/ask?test=test1
Console.WriteLine(url4.RemoveSlash()); // https://stackoverflow.com/questions/ask?test=test1
  •  Tags:  
  • c#
  • Related