Last updated: Mar 6, 2024
Reading timeยท2 min
To get the user's locale in the browser, access the first element of the
languages
property on the navigator
object, e.g. navigator.languages[0]
.
The property returns an array of strings that represent the user's preferred languages.
const userLocale = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language; console.log(userLocale); // ๐๏ธ "en-US" // ๐๏ธ ["en-US", "en", "de"] console.log(navigator.languages);
We used the navigator.languages property to get an array containing the user's preferred languages.
The languages are described using BCP 47 tags (tags for identifying languages).
Internet Explorer
does not support
the navigator.languages
property, so we used a ternary operator to
conditionally check if the property is available in the given browser.
The ternary operator is
very similar to an if/else
statement.
If the navigator.languages
property is not supported in the browser, we fall
back to the
navigator.language
property.
The property returns a string that represents the user's preferred language. This is usually the language of the user's browser UI.
// ๐๏ธ ["en-US", "en", "de"] console.log(navigator.languages); // "en-US" console.log(navigator.language);
Examples of the value of the languages
property include - en
, en-US
, fr
,
fr-FR
, etc.
If the navigator.languages
property is supported in the browser, the first
element in the array of languages will most commonly be the value stored by the
navigator.language
property.
You can learn more about the related topics by checking out the following tutorials: