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;
}