Skip to content

Instantly share code, notes, and snippets.

@leipert
Forked from anonymous/detectBrowserLanguage.js
Last active March 11, 2024 02:10
Show Gist options
  • Save leipert/9586b796281faa5e27ed to your computer and use it in GitHub Desktop.
Save leipert/9586b796281faa5e27ed to your computer and use it in GitHub Desktop.
Detect browser language in javascript (utilizing lodash)
// These window.navigator contain language information
// 1. languages -> Array of preferred languages (eg ["en-US", "zh-CN", "ja-JP"]) Firefox^32, Chrome^32
// 2. language -> Preferred language as String (eg "en-US") Firefox^5, IE^11, Safari,
// Chrome sends Browser UI language
// 3. browserLanguage -> UI Language of IE
// 4. userLanguage -> Language of Windows Regional Options
// 5. systemLanguage -> UI Language of Windows
var browserLanguagePropertyKeys = ['languages', 'language', 'browserLanguage', 'userLanguage', 'systemLanguage'];
var availableLanguages = ['de', 'ar'];
var detectedLocale = _.chain(window.navigator)
.pick(browserLanguagePropertyKeys) //Get only language properties
.values() //Get values of the properties
.flatten() //flatten all arrays
.compact() //Remove undefined values
.map(function (x) {
return x.substr(0, 2); //Shorten strings to use two chars (en-US -> en)
})
.find(function (x) {
return _.contains(availableLanguages, x); //Returns first language matched in available languages
})
.value();
var locale = detectedLocale || 'en'; //If no locale is detected, fallback to 'en'
@Raidus
Copy link

Raidus commented Jul 5, 2019

Thanks for the code! In my current lodash version 4.17.11 i need to change _.contains to _.includes

@leipert
Copy link
Author

leipert commented Jul 5, 2019

@Raidus I'd probably do it with native Javascript ES6 features now:

var availableLanguages = ["de", "ar"];

var locale =
  [
    ...(window.navigator.languages || []),
    window.navigator.language,
    window.navigator.browserLanguage,
    window.navigator.userLanguage,
    window.navigator.systemLanguage
  ]
    .filter(Boolean)
    .map(language => language.substr(0, 2))
    .find(language => availableLanguages.includes(language)) || "en";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment