Language name from ISO 639-1 code in Javascript

16,511

Solution 1

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"

Solution 2

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

Solution 3

If you want a name of an arbitrary language in an arbitrary language (e.g, 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.

Solution 4

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.

Solution 5

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>
Share:
16,511
aberaud
Author by

aberaud

Updated on June 05, 2022

Comments

  • aberaud
    aberaud about 2 years

    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 ?