Replace last folder name in a URL for language switch

Viewed 64

I'm looking for a simple method to switch a static multilingual website. The files have the same name in all languages, but are in different folders that are named with the language code (en, fr, es, de, ...).

Example:

mydomain.com/showcase/en/index.html
mydomain.com/showcase/fr/index.html

Now the visitor should be able to choose a different language with a language switcher. Which languages are available should remain open.

So the code has to jump from the end of the URL to the last / and then replace the previous two characters (no matter what it is, position -1 and -2 before the /) with the new language code. The language code will always be 2 digits and the language subdirectories are always at the end of the URL.

How do I get the new language code from the visitor's click? And how do I install it in the right place? How do I call the script in my html template?

Unfortunately, I'm a total beginner with js. I only know a little bit about html and css. I would be glad of a good code and an explanation of what it does exactly. I have found some partial solutions here, but none does exactly what I need.

thank you!

EDIT 15.7.2022 Someone seams not to understand the question :-) Well, I think it is very clear!

EDIT2 15.7.2022 I found how to do it (example in pseudocode):

First I get the URL

let url = window.location.href;

Then I get the filename

let filename = url.split('/').pop();

Then I split the url on the second last /

let base = url.substring(0, str.lastIndexOf("/") + 1);

Then I put it together with the new language code, for example "fr"

base + 'fr/' + filename

That should work, no? I have not searched yet for the correct syntax, so it is not tested. Oh, I see, the question is still closed ;-)

2 Answers

No ideas, really? After all, there are such ways to replace part of a link. To do this, look for a specific part, for example, "en" and replace it with "fr". Or better you search for "/en/" and replace it with "/fr/". In my case, I want to search for the LAST FOLDER, that is, the LAST "/**/" and replace it with "/fr/", or another language code chosen by the visitor. I just don't know how to code it and how to get the language code from the visitor click.

If you just simply replace the url, you can try using regex.

const url = 'mydomain.com/showcase/en/index.html';
const langs = ['fr', 'de', 'es'];

const multilingualUrl = (url, lang) => url.replace(/(?<=\/)(..)(?=\/)/g, lang);

langs.forEach(lang => console.log(`${lang} =>`, multilingualUrl(url, lang)));

Provides you with several ways to implement a multilingual website.

  1. Front-End JS (e.g. jquery.i18n)
  2. Server Side (e.g. i18n-node)
  3. Using a build tool like npm scripts or gulp (e.g. static-i18n)
Related