d45ndx
d45ndx

Reputation: 89

C# Remove a slash from a URL which is stored inside a var

I'm trying to remove a double slash from a string which is stored inside a variable.

I'm receiving the variable in the following way:

cService.CreateCommand("create invite")
    .Description("Creates a invite link for the server.")
    .Do(async (e) =>
    {
        var invite = await e.Server.CreateInvite(maxAge: null, maxUses: 25, tempMembership: false, withXkcd: false);
        await e.Channel.SendMessage(invite.Url);
    });

But the response inside this variable looks like the following URL:

https://discord.gg//rErYPJB

Which contains // in the end. But that URL does not exist. One slash has to be removed.

How could I remove one slash without affecting the https:// double slash?

I appreciate any kind of help.

Upvotes: 0

Views: 651

Answers (5)

Marco Luongo
Marco Luongo

Reputation: 387

errata corridge

string invite = "https://discord.gg//rErYPJB//rErYPJB//rErYPJB//rErYPJB//rErYPJB";

Console.WriteLine(
            invite.Substring(0, invite.IndexOf("://")+3) +  
            invite
            .Substring(invite.IndexOf("://") + 3, invite.Length - (invite.IndexOf("://") + 3))
            .Replace("//","/"));

Upvotes: 0

Striezel
Striezel

Reputation: 3758

Just do another replace for the https:// double slashes to add that slash again:

// replace all double slashes with single slash
string newUrl = invite.Url.Replace("//", "/");
// re-add removed slash for protocol
newUrl = newUrl.Replace(":/", "://");

It could also be done with one Replace() only, if the domain is always the same and the double slashes always appear at that very same place:

// replace double slashes with single slash
string newUrl = invite.Url.Replace("https://discord.gg//", "https://discord.gg/");

In any case, use the newUrl variable as parameter to SendMessage():

await e.Channel.SendMessage(newUrl);

Upvotes: 1

Farzin Kanzi
Farzin Kanzi

Reputation: 3435

Try this:

string invite = "https://discord.gg//rErYPJB";
        int lastIndex = invite.LastIndexOf("//");
        if (lastIndex >= 0)
            invite = invite.Remove(lastIndex, 1);

Upvotes: 2

user5326354
user5326354

Reputation:

You could use the Substring method to get 2 strings: https:// and discord.gg//rErYPJB. On the second string you could use the Replace and then append both strings back together

Upvotes: 0

Mark Slingerland
Mark Slingerland

Reputation: 21

I think you will always have a discord link, if this is true. This will be an easy solution:

invite.Remove(19, 1)

This will remove the 19th character of the var.

Upvotes: 1

Related Questions