1

I have a string pathname and an array of strings containing country extensions.

string url = "/pl/test-page/index.html";
string[] countryExtensions = {"/pl/", "/de/", "/tr/"};

What I want to achive is removing that part (/pl/ in the example) if exists in the given array.

if exists I simply want to receive the following url without repeating;

string newUrl = "/test-page/index.html";

Using that new url I want to print out some metacode only once just like below. I tried to use foreach but it then repeats the same metacode.

<link rel="alternate" hreflang="en-US" href="https://example.com/test-page/index.html" />
<link rel="alternate" hreflang="pl-PL" href="https://example.com/pl/test-page/index.html" />
<link rel="alternate" hreflang="de-DE" href="https://example.com/de/test-page/index.html" />
<link rel="alternate" hreflang="tr-TR" href="https://example.com/tr/test-page/index.html" />

How can I achieve that?

3
  • 1
    string newUrl = "/test-page/index.html"; Why is the / at the start still there? Wasn't it removed when you removed /pl/? Commented Jul 22, 2020 at 14:35
  • could you please post your foreach attempt? I really would like to see why it did not work. Do you have your urls in a separate collection? Commented Jul 22, 2020 at 14:37
  • @CaiusJard You're right, I needed to do this: Array.ForEach(countryExtensions, x => { url = url.Replace(x, ""); }); or you could set the countryExtensions.ToList().ForEach(x => { url = url.Replace(x, ""); }); Thank you for correcting me on that. Commented Jul 22, 2020 at 14:54

1 Answer 1

1

This gives you what you've asked for, but it seems a bit odd if it's what you want:

        string url = "/pl/test-page/index.html";
        string[] ext = {"/pl/", "/de/", "/tr/"};

        //remove the /pl/ and replace with /
        url = url.Replace(ext.FirstOrDefault(x => url.StartsWith(x)) ?? "/", "/");

        //build a list of urls /test.., /pl/test.., /de/test.. and /tr/test..
        var urls = new[] { url }.Concat(ext.Select(x => x.TrimEnd('/') + url));

You can use the urls to build your HTML (I didn't prefix the "https://example.com")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.