-
-
Save leipert/9586b796281faa5e27ed to your computer and use it in GitHub Desktop.
Detect browser language in javascript (utilizing lodash)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 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
Thanks for the code! In my current lodash version
4.17.11
i need to change_.contains
to_.includes