Get the User's Locale in the Browser using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.

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 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 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.