简体   繁体   中英

Language name from ISO 639-1 code in Javascript

I'm building a website where people can associate a language information to content.

The website uses Javascript heavily and the language information associated to various elements is treated internally as an ISO 639-1 code.

How to show a list of language names - in the language of the user ?

There are some similar questions on stackoverflow. I needed a javascript function for getting English names and Native names for different languages. I found a nice json formatted list of ISO 693-1 language codes on stackoverflow (based on wikipedia ) and created a gist with two functions getLanguageName and getLanguageNativeName . Here is how to use it:

getLanguageNativeName("cv"); // --> "чӑваш чӗлхи"
getLanguageName("cv"); // --> "Chuvash"
getLanguageNativeName("cv-RU"); // --> "чӑваш чӗлхи"
getLanguageName("cv-RU"); // --> "Chuvash"

I used it to answer another similar question: generate a list of localized language names with links to google translate

There is a native support for this in the new(ish) Intl API :

let languageNames = new Intl.DisplayNames(['en'], {type: 'language'});
languageNames.of('fr');      // "French"
languageNames.of('de');      // "German"
languageNames.of('fr-CA');   // "Canadian French"

If you want a name of an arbitrary language in an arbitrary language (eg, how to say "Korean language" in Japanese), you can use Unicode CLDR data.

To use it in JavaScript, you may use cldr NPM package like:

cldr.extractLanguageDisplayNames('it').en;
# => 'inglese'

But not sure if the package only supports Node.js or also supports browsers. If not, you may search for other libraries or write your own code to parse CLDR directly.

I think you are stuck with having to maintain your own list of mappings to native language names for each of the languages you wish to support. But it looks like Wikipedia has just what you need .

Another solution is to use iso-639-1 package .

Installation:

npm install iso-639-1

Usage in Node.js:

const ISO6391 = require('iso-639-1')
console.log(ISO6391.getAllCodes())  // ['aa', 'ab', ...]
console.log(ISO6391.getName('cv'))  // 'Chuvash'
console.log(ISO6391.getNativeName('cv'))  // 'чӑваш чӗлхи'

Usage in browsers:

<script type="text/javascript" src="./node_modules/iso-639-1/build/index.js"></script>
<script>
  console.log(ISO6391.getAllCodes())  // ['aa', 'ab', ...]
  console.log(ISO6391.getName('cv'))  // 'Chuvash'
  console.log(ISO6391.getNativeName('cv'))  // 'чӑваш чӗлхи'
</script>

Best Way:

 <script>
    var language = window.navigator.userLanguage || window.navigator.language; 
    alert(language);
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM