-1

I have a website with language preferences. When i click the button to change languages, everything works fine. The only issue is whenever I change the language, it takes the user right back to the homepage to http://localhost/en/ However, I have a page that is http://localhost/en/work, or http://localhost/en/work/#integrations. I can't figure out how to stay on the same page when I switch languages. I think it has something to do with split and replace, but I'm not sure. This is what I have so far.

That big if statement at the bottom is my failed attempt (very new here). Any suggestions?

languageOptions = ['en', 'zh-cn', 'zh-hk', 'jp-jp', 'ko-kr', 'th-th'];
languageDictionary = {
    'en': 'en',
    'en-gb': 'en',
    'en-us': 'en',
    'zh-cn': 'zh-cn',
} 


function checkLanguage() {
    let lang = localStorage.getItem('lang');  
    if (!lang) {
        lang = navigator.language.toLocaleLowerCase();
    }
    if (lang) {
        let userLang = languageDictionary[lang];

        let urlLang = window.location.pathname.split('/')[1];

        if (languageOptions.indexOf(urlLang) !== -1 && urlLang !== userLang) {
            changeLanguage(userLang);
        }
    }
};

checkLanguage();


function changeLanguage(lang) {
    if (languageOptions.indexOf(lang) === -1) {
        return;
    }
    localStorage.setItem('lang', lang);
    window.location.href = '/' + lang;
}

if (window.location.hash) {
    window.location.split('/')[1];
    window.location.replace[1](lang);
    window.location.href = '/' + lang + hash;
}
KatherineMichelle
  • 453
  • 10
  • 27

2 Answers2

-1

Plenty of ways to do it, but one way is just split, update, and join

var parts = window.location.href.split("/")
parts[3] = "foo"
window.location.href = parts.join("/")

You can do it with a regular expression, substrings, etc.

epascarello
  • 204,599
  • 20
  • 195
  • 236
-1

@epascarello is correct. You can use split and join to do what you need.

These are the issues you are having.

You are doing this.

let urlLang = window.location.pathname.split('/')[1];

Which returns an array of the url parts. If you where to use 'http://localhost/en/work/#integrations' it would return.

["http:", "", "localhost", "en", "work", "#integrations"]

What you want is this.

let urlLang = window.location.pathname.split('/');

Then assign the new lang.

urlLang[3] = 'newLang';

Then use it in you url.

window.location.href = urlLang.join("/");

Which would return 'http://localhost/newLang/work/#integrations'

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
  • **Which returns an array of the url parts"* - I don't think so, not with the `[1]` on the end of that line. – nnnnnn Nov 21 '17 at 10:15