demo
demo

Reputation: 6237

Remove additional slashes from URL

In ASP.Net it is posible to get same content from almost equal pages by URLs like localhost:9000/Index.aspx and localhost:9000//Index.aspx or even localhost:9000///Index.aspx

But it isn't looks good for me.

How can i remove this additional slashes before user go to some page and in what place?

Upvotes: 9

Views: 15673

Answers (7)

Agitech
Agitech

Reputation: 51

I use this in PowershellCore

$Uri -replace  "(?<!:)/{2,}", "/"

Upvotes: 0

LoremIpsum
LoremIpsum

Reputation: 1862

Here is the code snippets for combining URL segments, with the ability of removing the duplicate slashes:

    public class PathUtils
    {

        public static string UrlCombine(params string[] components)
        {
            var isUnixPath = Path.DirectorySeparatorChar == '/';

            
            for (var i = 1; i < components.Length; i++)
            {
                if (Path.IsPathRooted(components[i])) components[i] = components[i].TrimStart('/', '\\');
            }

            var url = Path.Combine(components);

            if (!isUnixPath)
            {
                url = url.Replace(Path.DirectorySeparatorChar, '/');
            }
            return Regex.Replace(url, @"(?<!(http:|https:))//", @"/");
        }
    }

Upvotes: 0

AuthorProxy
AuthorProxy

Reputation: 8047

Regex.Replace("http://localhost:3000///////asdasd/as///asdasda///asdasdasd//", @"/+", @"/").Replace(":/", "://")

Upvotes: 0

Bernhard
Bernhard

Reputation: 2799

see

https://stackoverflow.com/a/19689870

https://msdn.microsoft.com/en-us/library/9hst1w91.aspx#Examples

You need to specify a base Uri and a relative path to get the canonized behavior.

Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Console.WriteLine(myUri.ToString());

Upvotes: 6

Royi Namir
Royi Namir

Reputation: 148514

Use this :

url  = Regex.Replace(url  , @"/+", @"/");

it will support n times

enter image description here

Upvotes: 6

Jens
Jens

Reputation: 2702

This solution is not that pretty but very easy

do
{
    url = url.Replace("//", "/");
}
while(url.Contains("//"));

This will work for many slashes in your url but the runtime is not that great.

Upvotes: 1

L-Four
L-Four

Reputation: 13531

Remove them, for example:

 url = url.Replace("///", "/").Replace("//", "/");

Upvotes: 0

Related Questions