JavaScript to change language between WordPress Multisite

  javascript, jquery, php, wordpress, wordpress-theming

I am working on a multilingual WordPress multisite. It has more than 10 languages. I created a javascript that will redirect between 2 languages. To do that I have used location.pathname to get the current page URL. Then I split it to get the last directory name. I have used the if condition to check if the current URL of the page is in the second language.

For example, if I am on a page and then if I change the language to english. It will redirect me to Now the problem is If I add third language I am unable to figure out what condition should I use to switch between different languages. for example, If I am on a page and I want to switch to German. It should redirect from to

Every redirection should load the current page in requested language.

This a javascript code snippet to switch between two languages.

function myFunction() {
    var pathname = window.location.pathname;
    var page = pathname.split("/")[2];

    if ((lang = "fr/")) {
        location.replace(window.location.origin + "/" + page);

Source: Ask Javascript Questions