Get the User's Locale in the Browser using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 23 20221 min read

banner

Photo by Scott Webb

Get the User's Locale in the Browser using JavaScript #

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.

index.js
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).

The elements in the array are ordered by preference, with the most preferred language first.

Because Internet Explorer does not support the navigator.languages property, 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 expression to the left of the question mark returns a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

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.

index.js
// 👇️ ["en-US", "en", "de"] console.log(navigator.languages); // "en-US" console.log(navigator.language);

Examples for the value of this 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.