Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript's standard API to get the runtime's default locale?

In order to determine the current locale I found different approaches:

  1. Being in the browser, most people suggest looking at the HTTP headers (Accept-Language)
  2. Some people suggest consulting navigator.language
  3. Being in the backend (Node.js) and apart of HTTP, it is suggested to consult the (system dependent) process.env

On the other side, the ECMAScript Internationalization API defines the locales argument to each of the Intl constructors as optional:

If the locales argument is not provided or is undefined, the runtime's default locale is used.

So, it seems as if there should be a browser-independent and OS independent way to get "the runtime's default locale".

Is there a more straight forward way to get the runtime's default locale than

new Intl.NumberFormat().resolvedOptions().locale

?


The question How/Where does JavaScript detect the default locale? is different as it asks for the implementation of detecting the default locale (in a browser host). In contrast to that, my question is not about implementation but about the existence of a standard API.

like image 916
Min-Soo Pipefeet Avatar asked Mar 27 '19 19:03

Min-Soo Pipefeet


1 Answers

I'm not aware of a more straight-forward approach, but as you have already pointed out,

  1. new Intl.NumberFormat().resolvedOptions().locale is a solution

  2. DefaultLocale is an abstract operation, which might or might not be implemented in the future.

Hence, I would argue for polyfilling this function as:

if (typeof DefaultLocale === "undefined") {
    function DefaultLocale() {
        return new Intl.NumberFormat().resolvedOptions().locale;
    }
}

So, your code will reasonably assume the existence and call this function. In some point in the future, when this function is implemented in a standard manner, you will be able to clean up by removing the chunk from above.

like image 110
Lajos Arpad Avatar answered Sep 29 '22 16:09

Lajos Arpad