How To Get The User’s Locale In The Browser Using JavaScript

Solution To Get The User’s Locale In The Browser Using JavaScript

To get the user’s locale in the Browser using JavaScript, we will use navigator.language or navigator.languages ​​property depending on your habits. Here are specific steps I use these two properties. Let’s follow them.

Get the user’s locale in the Browser using JavaScript

First of all we will learn about two properties: navigator.language and navigator.languages.

Navigator.language property

Syntax:

navigator.language

Return Value: Returns the language your Browser is using.

Navigator.languages property

Syntax:

navigator.languages

Return Value: Returns an array containing the user’s favorite languages.

Use a conditional statement

We can use the IF conditional statement to check if the navigator.languages ​​property is an empty string. Otherwise, we can get your Browser’s preferred languages ​​from which to get the language, are used by taking the first value of the return array. If any, we will run and call the navigator.language property to get the user language.

Example:

if (navigator.languages != undefined) 
  console.log(navigator.languages[0]); // navigator.languages = ['en', 'vi', 'vi-VN', 'fr-FR', 'fr', 'en-US']

else
  console.log(navigator.language); //'en'

Output:

en

In this example, when we take the first element out, its value is equivalent to the return value of the navigator.language property. Because the first value of the array will be the language used by the Browser.

Use Conditional (Ternary) Operator

We use the Conditional (Ternary) Operator to do the same things as the conditional statement.

Syntax:

(condition) ? x : y

Parameters:

  • x: is the code to be called when the previous condition is true.
  • y: is the code to be called when the previous condition is false.

Example:

navigator.languages != undefined ? 
console.log(navigator.languages[0]): 
console.log(navigator.languages);

Output:

en

Because they run in a browser, the result of the ternary operator is the same as the conditional statement. So the navigator returns the navigator.languages ​​property is also an array of 6 elements.

The reason we prefer using the navigator.languages ​​property over the navigator.language property is because it ​​contains a list of languages ​​by priority which will be more precise than the navigator.language. The navigator.languages ​​property can return undefined or is an empty array, so we have to use conditions to prevent this from happening and avoid outputting an unsatisfactory value.

Summary

In this article, I have introduced some ways to get the user’s locale in the Browser using JavaScript. Then you can understand the string and remember it longer. I hope this post will be of help to you and your program. Good luck.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *