0

I want to use this piece of JavaScript so that, depending on the browser language of the visitor, a specific page is shown. The default should be English, so if the language isn´t one of the 5 languages that are set in the script, it should automatically select English. At the moment, it doesn´t seem to do so. Can anyone modify this piece of code for me so that it does just that?

var langcodes = ["es", "ca", "en" ,"nl", "fr", "de"];
var langCode = navigator.language || navigator.systemLanguage;
var lang = langCode.toLowerCase();
lang = lang.substr(0,2);
var dest = window.location.href;
for (i = langcodes.length-1; i >= 0; i--) {
    if (lang == langcodes[i]) {
        dest = dest.substr(0,dest.lastIndexOf('.')) + '-' + lang.substr(0,2) +
            dest.substr(dest.lastIndexOf('.'));
        window.location.replace ?
            window.location.replace(dest) :
            window.location=dest;
    }
}
1

1 Answer 1

1

A quick turnarounnd without looping and if/else would be,

var langCode = navigator.language || navigator.systemLanguage;
var lang = langCode.toLowerCase();
lang = lang.substr(0,2);

var langs = {
"es" : "xyz.com/es.html",
"ca": "xyz.com/ca.html",
"nl": "xyz.com/nl.html",
"en": "xyz.com/en.html"
}

if(typeof langs[lang] == 'undefined'){
window.location = "xyz.com/en.html";
}
else{
window.location = langs[lang];
}
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.